If you have two threads within an application, and you don't want them to run a certain piece of code simultaneously, you can just put a lock around the piece of code, like this:
lock (someObject) {
// ... some code
}
But how do you do the same thing across separate processes? I thought this is what you use a "global mutex" for, so I tried the Mutex
class in various ways, but it doesn't seem to fulfill my requirements, which are:
- If you're the only instance, go ahead and run the code.
- If you're the second instance, wait for the first one to finish, then run the code.
- Don't throw exceptions.
Problems I ran into:
- Just instantiating a
Mutex
object in ausing(){...}
clause doesn't seem to do anything; the two instances still happily run concurrently - Calling
.WaitOne()
on the Mutex causes the first instance to run and the second to wait, but the second waits indefinitely, even after the first calls.ReleaseMutex()
and leaves theusing(){}
scope. .WaitOne()
throws an exception when the first process exits (System.Threading.AbandonedMutexException
).
How do I solve this? Solutions that don't involve Mutex
are very welcome, especially since Mutex
appears to be Windows-specific.