Skip to content

Commit a6329c3

Browse files
committed
AsyncLock improvements and additional tests
1 parent eecaf68 commit a6329c3

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

Main/src/Threading/AsyncLock.cs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,15 @@ public Task<IDisposable> Acquire(int timeout, CancellationToken cancellation) =>
7272
[ItemNotNull]
7373
public Task<IDisposable> Acquire(TimeSpan timeout) => Acquire(timeout, CancellationToken.None);
7474

75+
/// <summary>
76+
/// Acquires async lock.
77+
/// </summary>
78+
/// <param name="cancellation">The CancellationToken token to observe.</param>
79+
/// <returns>A task that returns <see cref="IDisposable"/> to release the lock.</returns>
80+
[NotNull]
81+
[ItemNotNull]
82+
public Task<IDisposable> Acquire(CancellationToken cancellation) => Acquire(-1, cancellation);
83+
7584
/// <summary>
7685
/// Acquires async lock.
7786
/// </summary>

Main/tests/Threading/AsyncLockTest.cs

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
1-
using System.Diagnostics;
1+
using System;
2+
using System.Diagnostics;
3+
using System.Diagnostics.CodeAnalysis;
24
using System.Linq;
5+
using System.Threading;
36
using System.Threading.Tasks;
47

58
using NUnit.Framework;
@@ -39,5 +42,36 @@ await Enumerable
3942
Assert.IsFalse(opActive);
4043
Assert.GreaterOrEqual(sw.ElapsedMilliseconds, time * count + timeInc * count / 2);
4144
}
45+
46+
[Test]
47+
[SuppressMessage("ReSharper", "MethodSupportsCancellation")]
48+
public async Task Cancellation()
49+
{
50+
var cts = new CancellationTokenSource();
51+
var lck = new AsyncLock();
52+
const int delay = 5000;
53+
const int ensureLockInterval = 30;
54+
Task.Run(
55+
async () =>
56+
{
57+
using (await lck.Acquire())
58+
await Task.Delay(delay);
59+
});
60+
await Task.Delay(ensureLockInterval);
61+
var sw = Stopwatch.StartNew();
62+
var task = Task.Run(
63+
async () =>
64+
{
65+
using (await lck.Acquire(cts.Token))
66+
sw.Stop();
67+
});
68+
cts.Cancel();
69+
try
70+
{
71+
await task;
72+
}
73+
catch (TaskCanceledException) {}
74+
Assert.Less(sw.ElapsedMilliseconds, delay - ensureLockInterval);
75+
}
4276
}
4377
}

0 commit comments

Comments
 (0)