using System; using System.Threading; class Program { static Mutex mutex = new Mutex(); static void Main(string[] args) { if (!mutex.WaitOne(TimeSpan.FromSeconds(5), false)) { Console.WriteLine("Another instance of this application is already running."); return; } // Do some work here... mutex.Close(); } }
using System; using System.Threading; class Program { static Mutex mutex = new Mutex(); static void Main(string[] args) { try { if (!mutex.WaitOne(TimeSpan.FromSeconds(5), false)) { Console.WriteLine("Another instance of this application is already running."); return; } // Do some work here... } finally { mutex.Close(); } } }In this example, we use a try-finally block to ensure that the Close() method is always called, even if an exception is thrown while the mutex is held. The System.Threading.Mutex.Close() method is part of the .NET framework's System.Threading namespace.