Thursday, December 19, 2013

Cross process locking using a named mutex in C#

I needed to have some code be protected that only one process can execute it at a given time across processes. To do this I have used a featured called named mutexes in C# and .NET 4.5 (however you can do this in earlier versions. To make the code nice I wrote some little helpers as seen there

    public class CrossProcessLockFactory
    {
        private static int DefaultTimoutInMinutes = 2;
        public static IDisposable CreateCrossProcessLock()
        {
            return new ProcessLock(TimeSpan.FromMinutes(DefaultTimoutInMinutes));
        }

        public static IDisposable CreateCrossProcessLock(TimeSpan timespan)
        {
            return new ProcessLock(timespan);
        }
    }

    public class ProcessLock : IDisposable
    {
        // the name of the global mutex;
        private const string MutexName = "FAA9569-7DFE-4D6D-874D-19123FB16CBC-8739827-[SystemSpecicString]";

        private Mutex _globalMutex;

        private bool _owned = false;
        

        public ProcessLock(TimeSpan timeToWait)
        {
            try
            {
                _globalMutex = new Mutex(true, MutexName, out _owned);
                if (_owned == false)
                {
                    // did not get the mutex, wait for it.
                    _owned = _globalMutex.WaitOne(timeToWait);
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError(ex.Message);
                throw;
            }
        }

        public void Dispose()
        {
            if (_owned)
            {
                _globalMutex.ReleaseMutex();
            }            
            _globalMutex = null;
        }
    }

client code would look something like this:

    class Program
    {
        static void Main(string[] args)
        {
            using (CrossProcessLockFactory.CreateCrossProcessLock())
            {
                // if we get out it is ready
                Console.WriteLine("Using the mutex on process 1. Press any key to release the mutex");
                Console.ReadLine();
            }
        }
    }

This code can be improved to change the mutex name and the timespan from the client code. However for my needs this did the trick.

Update...

It is possible that a process that is holding a lock and owning the mutex dies. In this case the waiting process throws an exception of type AbandonedMutexException . It is a good idea to catch this exception, the process that catches this exception automatically owns the mutex now...

11 comments:

  1. I am using your code. But when multiple applications calling this method only one thread is getting this lock and others are always in waiting state. I want it to be shared equally between threads.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. Really great post, Thank you for sharing This knowledge.Excellently written article, if only all bloggers offered the same level of content as you, the internet would be a much better place. Please keep it up!
    python interview questions and answers
    python tutorials
    python course institute in electronic city

    ReplyDelete
  4. After reading this web site I am very satisfied simply because this site is providing comprehensive knowledge for you to audience.
    Thank you to the perform as well as discuss anything incredibly important in my opinion. We loose time waiting for your next article writing in addition to I beg one to get back to pay a visit to our website in




    Selenium training in bangalore
    Selenium training in Chennai
    Selenium training in Bangalore
    Selenium training in Pune
    Selenium Online training

    ReplyDelete
  5. This is a nice article here with some useful tips for those who are not used-to comment that frequently. Thanks for this helpful information I agree with all points you have given to us. I will follow all of them.
    AWS Training in Bangalore
    AWS training in sholinganallur
    AWS training in Tambaram
    AWS training in Velachery

    ReplyDelete
  6. This comment has been removed by the author.

    ReplyDelete
  7. Really very happy to say, your post is very interesting to read. I never stop myself to say something about it. You’re doing a great job. Keep it up…

    Get Web Methods Training in Bangalore from Real Time Industry Experts with 100% Placement Assistance in MNC Companies. Book your Free Demo with Softgen Infotech.

    ReplyDelete
  8. Thanks for one marvelous posting! I enjoyed reading it; you are a great author. I will make sure to bookmark your blog and may come back someday. I want to encourage that you continue your great posts.

    sap hybris training in bangalore

    sap scm training in bangalore

    sap pm training in bangalore

    sap crm training in bangalore

    sap ewm training in bangalore

    ReplyDelete