How to ensure only one instance of application should run in C#

It can be achieved by using mutex.
A Mutex is a mutually exclusive flag. It acts as a gate keeper to a section of code allowing one thread in and blocking access to all others. This ensures that the code being controlled will only be hit by a single thread at a time. Just be sure to release the mutex when you are done.
Below is the sample program:
In this program I am creating a mutex which is taking care of single instance of application should run.
There are three parameter  
1.     initallyOwned:- Boolean value(true)
2.    Name - string
3.    Creatednew – out parameter Boolean value
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Threading;

namespace Questions
    {
        static class Program
        {
            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            [STAThread]
            static void Main()
            {
                bool mutexCreated = false;
                System.Threading.Mutex mutex = new System.Threading.Mutex( true, @"QuestionProgram", out mutexCreated );
                               
                if (!mutexCreated)
                {
                    MessageBox.Show("QuestionProgram is already running.");
                }
                else
                {
                    // The usual stuff with Application.Run()

                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new Form1());

                    mutex.Close();
                }
            }
           
        }
        
    }


How to ensure only one instance of application should run in C# How to ensure only one instance of application should run in C# Reviewed by kamal kumar das on June 18, 2015 Rating: 5

No comments:

ads 728x90 B
Powered by Blogger.