Skip to content

Commit 8d72ffe

Browse files
committed
Switching back to Monitor-based locking in AsyncLockQueueDictionary
1 parent 0000326 commit 8d72ffe

File tree

1 file changed

+19
-17
lines changed

1 file changed

+19
-17
lines changed

Synchronisation.cs

Lines changed: 19 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@ namespace AsyncToSyncCodeRoundtripSynchroniserMonitor
1010
{
1111
public class AsyncLockQueueDictionary
1212
{
13-
//private readonly object DictionaryAccessMutex = new object();
14-
private readonly SemaphoreSlim DictionaryAccessMutex = new SemaphoreSlim(1, 1);
13+
private readonly object DictionaryAccessMutex = new object();
14+
//private readonly SemaphoreSlim DictionaryAccessMutex = new SemaphoreSlim(1, 1);
1515
private readonly Dictionary<string, AsyncLockWithCount> LockQueueDictionary = new Dictionary<string, AsyncLockWithCount>();
1616

1717
public sealed class AsyncLockWithCount
@@ -51,9 +51,9 @@ private void ReleaseLock(string name, AsyncLockWithCount lockEntry, IDisposable
5151
{
5252
lockHandle.Dispose();
5353

54-
//lock (DictionaryAccessMutex)
55-
DictionaryAccessMutex.Wait();
56-
try
54+
lock (DictionaryAccessMutex)
55+
//DictionaryAccessMutex.Wait();
56+
//try
5757
{
5858
lockEntry.WaiterCount--;
5959
Debug.Assert(lockEntry.WaiterCount >= 0);
@@ -63,33 +63,35 @@ private void ReleaseLock(string name, AsyncLockWithCount lockEntry, IDisposable
6363
LockQueueDictionary.Remove(name);
6464
}
6565
}
66-
finally
67-
{
68-
DictionaryAccessMutex.Release();
69-
}
66+
//finally
67+
//{
68+
// DictionaryAccessMutex.Release();
69+
//}
7070
}
7171

7272
public async Task<LockDictReleaser> LockAsync(string name, CancellationToken cancellationToken = default(CancellationToken))
7373
{
7474
AsyncLockWithCount lockEntry;
75-
//lock (DictionaryAccessMutex)
76-
await DictionaryAccessMutex.WaitAsync(cancellationToken);
77-
try
75+
#pragma warning disable PH_S023 //Message PH_S023 Using the blocking synchronization mechanics of a monitor inside an async method is discouraged; use SemaphoreSlim instead.
76+
lock (DictionaryAccessMutex)
77+
#pragma warning restore PH_S023
78+
//await DictionaryAccessMutex.WaitAsync(cancellationToken);
79+
//try
7880
{
7981
if (!LockQueueDictionary.TryGetValue(name, out lockEntry))
8082
{
81-
lockEntry = new AsyncLockWithCount();
83+
lockEntry = new AsyncLockWithCount();
8284
LockQueueDictionary.Add(name, lockEntry);
8385
}
8486
else
8587
{
8688
lockEntry.WaiterCount++; //NB! must be done inside the lock and BEFORE waiting for the lock
8789
}
8890
}
89-
finally
90-
{
91-
DictionaryAccessMutex.Release();
92-
}
91+
//finally
92+
//{
93+
// DictionaryAccessMutex.Release();
94+
//}
9395

9496
var lockHandle = await lockEntry.LockEntry.LockAsync(cancellationToken);
9597
return new LockDictReleaser(name, lockEntry, lockHandle, this);

0 commit comments

Comments
 (0)