One problem you may face is the need to check if an application is already running or not. You may not want a user to run multiple instances of an application for various reasons.
So, how does one go about doing this?
You can use the Mutex class. Yes, Mutex. While this if a funny name it does have its purpose.
To read more about Mutex, click ‘here’
Basic summation of what Mutex is: A synchronization primitive that can also be used for interprocess synchronization.
So what does this mean? Basically, Mutex will provide the same functionality as the lock statement. This really means that Mutex is a bit redundant, however there is one advantage that Mutex has over lock:
Mutex provides a computer-wide lock versus just an application-wide lock.
So, this is really cool!
How will this work in our application? Let’s cut to the chase and look at code.
I have created a sample application called ThreadingConsole. My assembly and namespace are ThreadingConsole for consistency.
Now, I know you are really here to just see code that works and not read a bunch of mumbo jumbo about how it is supposed to work. Without further ado, the code:
using System; using System.Threading; namespace ThreadingConsole { class Program { private static readonly Mutex AppMutex = new Mutex(false, "ThreadingConsole"); static void Main(string[] args) { if(!AppMutex.WaitOne(TimeSpan.FromSeconds(5), false)) { Console.WriteLine("Another instance of the app is currently running."); Console.WriteLine("Hit any key to exit"); Console.ReadLine(); return; } Console.WriteLine("Running - hit any key to exit"); Console.ReadLine(); } } }
Now that you have the code, you can copy and paste this into your application, build it. Navigate to your bin/debug directory. Launch the application and then launch it again. You will find that the 2nd instance will give you the proper error message and you can move on.
Exciting huh?
So, this post was not to explain the nitty gritty of what Mutex is (that is what the click ‘here’ link is for).
I hope you found this useful.
Happy programming.
