| 1 |
using System; |
| 2 |
using System.Runtime.CompilerServices; |
| 3 |
using System.Threading; |
| 4 |
using System.Threading.Tasks; |
| 5 |
|
| 6 |
namespace GodotTools.IdeMessaging.Utils |
| 7 |
{ |
| 8 |
public static class SemaphoreExtensions |
| 9 |
{ |
| 10 |
public static ConfiguredTaskAwaitable<IDisposable> UseAsync(this SemaphoreSlim semaphoreSlim, CancellationToken cancellationToken = default(CancellationToken)) |
| 11 |
{ |
| 12 |
var wrapper = new SemaphoreSlimWaitReleaseWrapper(semaphoreSlim, out Task waitAsyncTask, cancellationToken); |
| 13 |
return waitAsyncTask.ContinueWith<IDisposable>(t => wrapper, cancellationToken).ConfigureAwait(false); |
| 14 |
} |
| 15 |
|
| 16 |
private readonly struct SemaphoreSlimWaitReleaseWrapper : IDisposable |
| 17 |
{ |
| 18 |
private readonly SemaphoreSlim semaphoreSlim; |
| 19 |
|
| 20 |
public SemaphoreSlimWaitReleaseWrapper(SemaphoreSlim semaphoreSlim, out Task waitAsyncTask, CancellationToken cancellationToken = default(CancellationToken)) |
| 21 |
{ |
| 22 |
this.semaphoreSlim = semaphoreSlim; |
| 23 |
waitAsyncTask = this.semaphoreSlim.WaitAsync(cancellationToken); |
| 24 |
} |
| 25 |
|
| 26 |
public void Dispose() |
| 27 |
{ |
| 28 |
semaphoreSlim.Release(); |
| 29 |
} |
| 30 |
} |
| 31 |
} |
| 32 |
} |