I have an application where I have a shared resource (a Motion system) which can be accessed by multiple clients. I have individual Operations that require access to the sy
There's SemaphoreSlim.WaitAsync which fits closely here. (I found it in a similar question).
My question: does anybody know of a good pattern to deal with acquiring exclusive access in the presence of thread switching due to async/await?
Yes, you can use AsyncLock, which is also available as part of my AsyncEx library. If you want to have a "TryLock" kind of operation, then you may have to create your own primitive.
You do lose some of the capability to do safety checks: there is no way to check whether the currently-executing thread has a specific AsyncLock
.
Other options include ConcurrentExclusiveSchedulerPair
(which I blog about here) or TPL Dataflow.