-
Notifications
You must be signed in to change notification settings - Fork 762
/
Copy pathAsyncGate.cs
63 lines (52 loc) · 1.69 KB
/
AsyncGate.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT License.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Threading.Tasks;
namespace System.Threading
{
public sealed class AsyncGate
{
private readonly object _gate = new();
private readonly SemaphoreSlim _semaphore = new(1, 1);
private readonly AsyncLocal<int> _recursionCount = new();
public ValueTask<Releaser> LockAsync()
{
var shouldAcquire = false;
lock (_gate)
{
if (_recursionCount.Value == 0)
{
shouldAcquire = true;
_recursionCount.Value = 1;
}
else
{
_recursionCount.Value++;
}
}
if (shouldAcquire)
{
return new ValueTask<Releaser>(_semaphore.WaitAsync().ContinueWith(_ => new Releaser(this)));
}
return new ValueTask<Releaser>(new Releaser(this));
}
private void Release()
{
lock (_gate)
{
Debug.Assert(_recursionCount.Value > 0);
if (--_recursionCount.Value == 0)
{
_semaphore.Release();
}
}
}
public readonly struct Releaser : IDisposable
{
private readonly AsyncGate _parent;
public Releaser(AsyncGate parent) => _parent = parent;
public void Dispose() => _parent.Release();
}
}
}