I was looking for an awaitable equivalent of lock statements in C#. Some people suggest using a binary SemaphoreSlim
in the following way:
await semaphore.WaitAsync().ConfigureAwait(false);
try
{
//inner instructions
}
finally
{
semaphore.Release();
}
I know it has some issues (e.g. it's not reentrant), but my biggest concern is with the instruction reeordering.
In plain old lock statements we have a guarantee that no inner instruction from the lock will be moved outside (before or after) the lock statement. Does the same hold for this semaphore solution? As far as I can see, the documentation doesn't mention this problem.
SemaphoreSlim
, and pretty much all of the other synchronization constructs, are built using a Monitor
(or other types that are built on top of a Monitor
) internally, which is exactly how a lock
is implemented, giving you the same guarantees.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With