This is a small post about refactoring lock statements in async methods.
lock
async
Before refactoring we had a code like this:
lock(sync) { result = methodToRefactorIntoAsync(); } ... private object sync = new object();
Lock is bound to a thread, thus no way you to use it in async code. As an alternative you may use SemaphoreSlim class:
await sync.WaitAsync(cancellationToken); try { result = await methodAsync(cancellationToken); } finally { sync.Release(); } ... private SemaphoreSlim sync = new SemaphoreSlim(1, 1);
Remember Me
a@href@title, b, blockquote@cite, em, i, strike, strong, sub, super, u