Skip to content

Commit da087c2

Browse files
committed
Fix task scheduling race condition in AsyncLock.Dispose()
Closes #18.
1 parent 4c886f8 commit da087c2

File tree

1 file changed

+18
-21
lines changed

1 file changed

+18
-21
lines changed

AsyncLock/AsyncLock.cs

Lines changed: 18 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -299,32 +299,29 @@ public void Dispose()
299299
var @this = this;
300300
var oldId = this._oldId;
301301
var oldThreadId = this._oldThreadId;
302-
Task.Run(async () =>
302+
@this._parent._reentrancy.Wait();
303+
try
303304
{
304-
await @this._parent._reentrancy.WaitAsync();
305-
try
305+
Interlocked.Decrement(ref @this._parent._reentrances);
306+
@this._parent._owningId = oldId;
307+
@this._parent._owningThreadId = oldThreadId;
308+
if (@this._parent._reentrances == 0)
306309
{
307-
Interlocked.Decrement(ref @this._parent._reentrances);
308-
@this._parent._owningId = oldId;
309-
@this._parent._owningThreadId = oldThreadId;
310-
if (@this._parent._reentrances == 0)
310+
// The owning thread is always the same so long as we
311+
// are in a nested stack call. We reset the owning id
312+
// only when the lock is fully unlocked.
313+
@this._parent._owningId = UnlockedId;
314+
@this._parent._owningThreadId = (int)UnlockedId;
315+
if (@this._parent._retry.CurrentCount == 0)
311316
{
312-
// The owning thread is always the same so long as we
313-
// are in a nested stack call. We reset the owning id
314-
// only when the lock is fully unlocked.
315-
@this._parent._owningId = UnlockedId;
316-
@this._parent._owningThreadId = (int)UnlockedId;
317-
if (@this._parent._retry.CurrentCount == 0)
318-
{
319-
@this._parent._retry.Release();
320-
}
317+
@this._parent._retry.Release();
321318
}
322319
}
323-
finally
324-
{
325-
@this._parent._reentrancy.Release();
326-
}
327-
});
320+
}
321+
finally
322+
{
323+
@this._parent._reentrancy.Release();
324+
}
328325
}
329326
}
330327

0 commit comments

Comments
 (0)