Hence I can\'t use thread-affine locks with async
- how can I guard my resources when running multiple processes?
For example I\'ve two processes that u
I've got an interesting solution for you. Don't have time to provide a code sample right now, so if my description isn't enough let me know and I'll try and provide code.
You've got two problems here. First, an AsyncMutex doesn't have thread affinity, as you've pointed out. So you can't build one out of a Mutex. You can, however, build one out of a Semaphore with a count of 1, since a semaphore doesn't have thread affinity either. In C# the Semaphore class can be named and used across process boundaries. So the first issue is fairly easily solved.
The second problem is in not wanting to use blocking calls when you "lock" this AsyncMutex. Well, you can use ThreadPool.RegisterWaitForSingleObject to register a callback to be executed when the Semaphore (a WaitHandle) is signaled. This does an "asynchronous wait". Wrap that with a bit of code using a TaskCompletionSource and you can build a Task returning WaitAsync method on your AsyncMutex fairly easily. These two ideas should make it fairly easy to implement a cross process named AsyncMutex usable in C#.
Keep in mind that like other AsyncMutex implementations you'll find, this won't be a recursive mutex (the same "thread" can lock the mutex multiple times so long as it unlocks the mutex the same number of times), so care must be taken in code to not cause deadlock.