10

When accessing critical section in C# with async/await keywords, using lock keyword or Monitor is generally not advised (Why can't I use the 'await' operator within the body of a lock statement?), because it introduces deadlock in the situation where thread that locked critical section section will possibly be not avaliable.

The general approach is to use SemaphoreSlim class.

My question is that since SemaphoreSlim(1,1) and lock are functionally the same, what is the reason that it's okay to use one, but the other introduces deadlock?

Is it because SemaphoreSlim can be released from any thread, while lock is "owned" exclusively by the thread that locked it?

aybe
  • 15,516
  • 9
  • 57
  • 105

1 Answers1

0

Is it because SemaphoreSlim can be released from any thread, while lock is "owned" exclusively by the thread that locked it?

Yes, this is the reason. The lock is thread-affine, while the SemaphoreSlim is not. The SemaphoreSlim doesn't care which thread releases it. On the contrary the lock would throw a SynchronizationLockException if somehow you managed to switch to another thread before exiting the lock. Which you can't, because the C# language doesn't allow an await inside a lock.

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104