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...

10 comments:

C Sharpens said...

Want to learn C# from basics & in most professional Code development style. I'll have you writing real working applications in no time flat-before you reach the end of course.
Hire C# Teacher.

Manjay said...

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.

Manjay said...
This comment has been removed by the author.
Smith said...

Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from .Net Core Training in Chennai. or learn thru .Net Core Training in Chennai. Nowadays Dot Net has tons of job opportunities on various vertical industry.
or Es6 Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.

afiah ahamed said...

This is an awesome post.Really very informative and creative contents. These concept is a good way to enhance the knowledge.I like it and help me to development very well.Thank you for this brief explanation and very nice information.Well, got a good knowledge.
Selenium training in Chennai

Selenium training in Bangalore

Saro said...

Very nice post here and thanks for it .I always like and such a super contents of these post.Excellent and very cool idea and great content of different kinds of the valuable information's.
rpa training in bangalore
best rpa training in bangalore
RPA training in bangalore
rpa course in bangalore
rpa training in chennai
rpa online training

john jersy said...

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

sathish said...

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

ragul ragul said...

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

Ananya M said...

Very useful content and also easily understandable providing. Your blog is really helpful for me.

AWS Course | AWS Course in Chennai | AWS Training in Chennai | AWS Training