threading & mutex: question about example

J

Jeroen

Hi all,

I've been trying to get my head around threading. Here's an example
from the book I'm reading:

/***************************/
Mutex m = null;
const string name = "xyz";

try
{
m = Mutex.OLpenExisting(name);
}
catch (WaitHandleCannotBeOpenedException)
{ }

if (m == null)
{
// POINT 'A'
m = new Mutex(true, name);
}
else
{
m.close();
return;
}
/*****************************/

This example can be used in the main method to prevent two instances
of the same application to be run.

Now, as a newbie to threading, it seems to me that theoretically two
threads might *both* get to "Point 'A'", correct?

Thanks, regards,
Jeroen
 
N

Nicholas Paldino [.NET/C# MVP]

Jeroen,

Yes, two threads might get to point 'A', but that's not really the
problem here. Because the Mutex is named, it is visible to other processes,
so you have to worry about another process opening the thread if it finds
out that it doesn't exist.

To be honest, this isn't the best way to open or create a Mutex which is
named, as you have this race condition.

It's a better idea to call the CreateMutex API function through the
P/Invoke layer, which will open or create the named mutex if it doesn't
exist. Then, with the handle returned from that function, you would set the
SafeWaitHandle property of a new Mutex instance to that handle and call the
appropriate methods.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top