/
AsyncLock.cs
89 lines (76 loc) · 2.43 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
//------------------------------------------------------------------------------
// <copyright file="AsyncLock.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.Web.Hosting.RewriteProvider.HttpScale
{
/// <summary>
/// Fast asynchronous lock that does zero allocations in the synchronous case.
/// </summary>
sealed class AsyncLock : IDisposable
{
private readonly SemaphoreSlim semaphore;
private readonly Task<Releaser> releaser;
public AsyncLock()
{
this.semaphore = new SemaphoreSlim(1);
this.releaser = Task.FromResult(new Releaser(this));
}
public Task<Releaser> LockAsync(int timeoutMs)
{
Task<bool> wait = this.semaphore.WaitAsync(timeoutMs);
if (wait.IsCompleted)
{
return this.releaser;
}
return wait.ContinueWith<Releaser>(
OnCompletedAsync,
this,
CancellationToken.None,
TaskContinuationOptions.ExecuteSynchronously,
TaskScheduler.Default);
}
public void Dispose()
{
this.semaphore.Dispose();
}
private static Releaser OnCompletedAsync(Task<bool> task, object state)
{
if (task.Result)
{
return new Releaser((AsyncLock)state);
}
return new Releaser(timedOut: true);
}
public struct Releaser : IDisposable
{
private readonly AsyncLock asyncLock;
private readonly bool timedOut;
internal Releaser(AsyncLock asyncLock)
{
this.asyncLock = asyncLock;
this.timedOut = false;
}
internal Releaser(bool timedOut)
{
this.timedOut = timedOut;
this.asyncLock = null;
}
public bool TimedOut
{
get { return this.timedOut; }
}
public void Dispose()
{
if (!this.timedOut)
{
this.asyncLock.semaphore.Release();
}
}
}
}
}