Drawing Blanks

Premature Optimization is a Prerequisite for Success

Archive for July 2010

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;
           try
           {
               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.");
           try
           {
               //
               // Do the stuff
               //
            }
           finally
           {
               if (mutexOwned)
                   mut.ReleaseMutex();
           }

Written by bbzippo

07/17/2010 at 8:16 pm

Posted in Uncategorized