Mutex - Make the program to start only once

Sometimes in the development process, it is necessary to run one and only one instance.
Mutex class, known as the body of each split is a synchronization primitive, it is only granted to a thread exclusive access to the shared resource.

When two or more threads simultaneously access a shared resource, the system need to use the synchronization mechanism to ensure that only one thread to use the resource.

If a thread to obtain a mutex, they have to get the mutex the second thread will be suspended until the first thread to release the mutex.

Here is an illustration Mutex class to ensure that there is only one instance of the application.

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace RunOnce
{
    
static class Program
    {
        
/// <summary>
        
/// Application's main entry point.
        
/// </summary>
        [STAThread]
        
static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(
false);

            
bool bCreate;
            System.Threading.Mutex mutex
= new System.Threading.Mutex(false, "SINGILE_INSTANCE_MUTEX", out bCreate);

            
if (bCreate)
            {
                Application.Run(
new Form1());
            }
            
else
            {
                MessageBox.Show(
"Process has started already.");
                Application.Exit();
            }
        }
    }
}

Post Rating

Comments
Only registered users may post comments.
Subscribe
Rss Feed Email Follow Us on Twitter
Search