Skip to content

Commit 455b9c8

Browse files
fredericDelaportehazzik
authored andcommitted
Updating AsyncLock according to blog source supplied by Cremor.
1 parent 1772a1e commit 455b9c8

File tree

2 files changed

+17
-75
lines changed

2 files changed

+17
-75
lines changed

src/NHibernate/Util/AsyncLock.cs

Lines changed: 17 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -4,44 +4,33 @@
44

55
namespace NHibernate.Util
66
{
7-
public class AsyncLock
7+
// Source from https://www.hanselman.com/blog/ComparingTwoTechniquesInNETAsynchronousCoordinationPrimitives.aspx
8+
public sealed class AsyncLock
89
{
9-
private readonly AsyncSemaphore semaphore;
10-
private readonly Task<Releaser> releaser;
10+
private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
11+
private readonly Task<IDisposable> _releaser;
1112

1213
public AsyncLock()
1314
{
14-
semaphore = new AsyncSemaphore(1);
15-
releaser = Task.FromResult(new Releaser(this));
15+
_releaser = Task.FromResult((IDisposable)new Releaser(this));
1616
}
1717

18-
public Task<Releaser> LockAsync()
18+
public Task<IDisposable> LockAsync()
1919
{
20-
var wait = semaphore.WaitAsync();
21-
return wait.IsCompleted
22-
? releaser
23-
: wait.ContinueWith(
24-
(_, state) => new Releaser((AsyncLock)state),
25-
this,
26-
CancellationToken.None,
27-
TaskContinuationOptions.ExecuteSynchronously,
28-
TaskScheduler.Default);
20+
var wait = _semaphore.WaitAsync();
21+
return wait.IsCompleted ?
22+
_releaser :
23+
wait.ContinueWith(
24+
(_, state) => (IDisposable)state,
25+
_releaser.Result, CancellationToken.None,
26+
TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
2927
}
3028

31-
public struct Releaser : IDisposable
29+
private sealed class Releaser : IDisposable
3230
{
33-
private readonly AsyncLock toRelease;
34-
35-
internal Releaser(AsyncLock toRelease)
36-
{
37-
this.toRelease = toRelease;
38-
}
39-
40-
public void Dispose()
41-
{
42-
if (toRelease != null)
43-
toRelease.semaphore.Release();
44-
}
31+
private readonly AsyncLock _toRelease;
32+
internal Releaser(AsyncLock toRelease) { _toRelease = toRelease; }
33+
public void Dispose() { _toRelease._semaphore.Release(); }
4534
}
4635
}
4736
}

src/NHibernate/Util/AsyncSemaphore.cs

Lines changed: 0 additions & 47 deletions
This file was deleted.

0 commit comments

Comments
 (0)