Just wrote a simple program that must be processed once at a time, so achieved this by using a keyed Mutex
with a particular name.
The code (simplified) looks like this.
static readonly string APP_NAME = "MutexSample";
static void Main(string[] args)
{
Mutex mutex;
try
{
mutex = Mutex.OpenExisting(APP_NAME);
// At this point, with no exception,
// the Mutex is acquired, so there is another
// process running
// Environment.Exit(1); or something
}
catch (WaitHandleCannotBeOpenedException)
{
// If we could not acquire any mutex with
// our app name, let's create one
mutex = new Mutex(true, APP_NAME);
}
Console.ReadKey(); // Just for keeping the application up
// At some point, I just want to release
// the mutex
mutex.ReleaseMutex();
}
My first attempt was instantiating the Mutex
like new Mutex(false, APP_NAME)
, but calling mutex.ReleaseMutex()
was throwing an exception
System.ApplicationException: 'Object synchronization method was called from an unsynchronized block of code.'
Just noticed that the first parameter of the constructor (initiallyOwned
) marks whether the current thread that is creating the Mutex
owns it and, unsurprisingly, a thread cannot release a Mutex
which is not owned by that thread.
So changing this parameter to true
fixed that issue, as shown on the code above.
Well, my question is, what is the whole point of that parameter? I mean, when will I need to create a Mutex
that I am not able to release it.
And, if I set the parameter initiallyOwned
to false
, who does really own that Mutex
?
Thanks.