Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

prevent a c# application from running more than one instance

Tags:

c#

process

I wrote a program in c# now I would like to know what is the proper way to prevent the program from starting if it is already running?

so if it is already running, and double-click on the program it will not start because it is already running.

I can do that, but I was thinking of a standard and proper way.

like image 672
Data-Base Avatar asked Aug 23 '10 06:08

Data-Base


People also ask

Why do I get sick from AC?

Contamination and Germs One cause of this could be central air conditioning circulating old stagnant air rather than bringing in fresh air from outside. Meaning that if there is mold, dust, animal dander, viruses, or airborne infections floating about, then individuals are more likely to be exposed and get sick.

Can cold AC make you sick?

Cold air doesn't make you sick. You must be exposed to germs, bacteria and viruses to get sick. An air conditioner, by itself, can't make you sick.

Why does AC hurt my throat?

An air conditioner takes moisture out of the air. If you are sensitive to dry air, it can cause a sore throat. This is especially true for people who suffer from allergies. When possible, consider opening the windows to allow more humid air into the home.


2 Answers

The recommended way to do this is with a system mutex.

bool createdNew;
using(var mutex = new System.Threading.Mutex(true, "MyAppName", out createdNew))
{
    if (createdNew)
        // first instance
        Application.Run();
    else
        MessageBox.Show("There is already an instace running");
}

The first parameter to the Mutex ctor tells it to give create a system wide mutex for this thread. If the Mutex already exists it will return out false through the 3rd parameter.

Update
Where to put this? I'd put this in program.cs. If you put it in form_load you'll need to keep the mutex for the life time of the application (have the mutex as a member on the form), and manually release it in the form unload.
The earlier you call this the better, before the other app opens DB connections etc. and before resources are put created for forms / controlls etc.

like image 152
Binary Worrier Avatar answered Sep 21 '22 11:09

Binary Worrier


Quick way I did in one of the applications .. You can look at the list of running processes to see whether the current application is already running and not start the application again.

Process[] lprcTestApp = Process.GetProcessesByName("TestApplication");
if (lprcTestApp.Length > 0)
{
      // The TestApplication is already running, don't run it again
}
like image 38
Premkumar Avatar answered Sep 19 '22 11:09

Premkumar