forked from SciSharp/LLamaSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAsyncLock.cs
55 lines (46 loc) · 1.56 KB
/
AsyncLock.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
namespace LLama.Web.Async
{
/// <summary>
/// Create an Async locking using statment
/// </summary>
public sealed class AsyncLock
{
private readonly SemaphoreSlim _semaphore;
private readonly Task<IDisposable> _releaser;
/// <summary>
/// Initializes a new instance of the <see cref="AsyncLock"/> class.
/// </summary>
public AsyncLock()
{
_semaphore = new SemaphoreSlim(1, 1);
_releaser = Task.FromResult((IDisposable)new Releaser(this));
}
/// <summary>
/// Locks the using statement asynchronously.
/// </summary>
/// <returns></returns>
public Task<IDisposable> LockAsync()
{
var wait = _semaphore.WaitAsync();
if (wait.IsCompleted)
return _releaser;
return wait.ContinueWith((_, state) => (IDisposable)state, _releaser.Result, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
/// <summary>
/// IDisposable wrapper class to release the lock on dispose
/// </summary>
/// <seealso cref="IDisposable" />
private sealed class Releaser : IDisposable
{
private readonly AsyncLock _lockToRelease;
internal Releaser(AsyncLock lockToRelease)
{
_lockToRelease = lockToRelease;
}
public void Dispose()
{
_lockToRelease._semaphore.Release();
}
}
}
}