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.
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.
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.
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.
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With