Drawing Blanks

Premature Optimization is a Prerequisite for Success

Lock pattern using mutex

leave a comment »

For some reason Microsoft doesn’t provide any examples for using mutexes in .Net in the same manner as we use monitors and the lock statements.

I think the following pattern works:

           Mutex mut = new Mutex(false, "Global\\MyMutex");
           bool mutexOwned = false;
               mutexOwned = mut.WaitOne(TimeSpan.FromSeconds(2), false);
           catch (AbandonedMutexException)
               //Eat AbandonedMutexException - the mutex will still be acquired
               //... but you may want to log this exception
               mutexOwned = true;
           if (!mutexOwned)
               throw new Exception("Could not acquire mutex within the timeout.");
               // Do the stuff
               if (mutexOwned)

Written by bbzippo

07/17/2010 at 8:16 pm

Posted in Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: