简体   繁体   中英

C# application close the first instance of itself

I know how to make sure that I run only one instance of an application at a time: How to check if another instance of the application is running

But... How can I make sure that when a second instance is started, the first instance will be closed (instead of just exiting the 2nd one which is usually done). And preferably waiting for it to be fully closed.

If more than 2 instances are started simultaneously then only the last one should be allowed to 'live'.

I got it (thanks you all the answers). My solution below:

        #region Kill other running processes of this application
        List<Process> processes = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).ToList();
        if (processes.Count > 1)
        {
            processes.Sort((x, y) => DateTime.Compare(x.StartTime, y.StartTime));
            for (int i = 0; i < processes.Count - 1; i++)
            {
                processes[i].CloseMainWindow();
                processes[i].WaitForExit();
            }
        }
        #endregion

        Console.WriteLine(string.Format("{0}:{1}", DateTime.Now.Minute, DateTime.Now.Second));
        Console.ReadLine();

You can use WindowsFormsApplicationBase class of Microsoft.VisualBasic.dll.

StartupNextInstance event is raised in first app when another instance is created. In this event you can kill current process.

 Process.GetCurrentProcess().Kill();

This will make sure that new instance is alive, and previous instances are closed.

There's probably a better way to do this involving other inter-communication between processes and events, but here's a basic method that requires no research(at least on my part)

When a process starts, make a file(maybe with a timestamp) to signal if it's started.

Have the original process check the file periodically, and stop it if it sees a newer timestamp

I think you are a little bit confused about the logic yourself. By the way here are some items you should use to do such a thing:

1- System.Diagnostics.Process.WaitForExit

With calling this method for a specific process instance, you can wait until the process is exited completely after you called the "Kill" or "Shutdown" method. It will close the main window in the process if it's a windows app. For the applications which have some confirmation boxes for exiting, it will wait until user confirm or cancel the dialog box (Like when your windows is shutting down while your applications are already open).

2- System.Diagnostics.Process.ExitCode

If you want to access the result of the exist message you send to a process, you should call the value of this property after calling "WaitForExit" function. I guess you can use this property to find out if the first process exited or not and with what reason from the second process.

3- public static int Main

Because you need to access the exit code from the outside of the process you should change the return value of "Main" method to int . This way you can return a value in the first process and access it in the second process through the "ExitCode" property. If returning a value in the "Main" function is difficult in your situation, you can pass the exit code by calling the 4th item.

4- System.Windows.Application.Shutdown (Exit in .NET < 4)

Calling this method does the exact thing as returning the value in the "Main" function.

5- System.Diagnostics.Process.GetProcessesByName

After all by calling this static method you can get all the processes by specified name.

Hope it helps. I just tried to explain everything as simple as possible. These all are the tools you can use to implement the logic. The rest would be so simple if you know these abilities that .NET provided for you.

After all, as I've already forgot to say, if you are interested in doing the right thing, in my opinion and as my experience says, there is a technology that has been made just for these kind of logics.

6- .NET Interprocess Communications or IPC ( a sample on code ) ( introduction on codeguru )

IPC is based on the .NET remoting (the most interesting discussion in .NET in my personal opinion) BUT regardless of what the name says, it's not only for remote communications. The remoting has many sections and on of those is the Inter-Process-Communication (IPC). It's the hard, but the best way if you ask me.

Cheers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM