简体   繁体   中英

Application.Restart leaves processes hanging

When a certain criteria is reached my application runs Application.Restart to restart the application. This leaves a process hanging so that when the application comes back up it complains that it is already running (I have code to check that only one instance of the application is allowed).

This process can be eliminated by calling Environment.Exit but this conflicts with Application.Restart. When Restart is called, and then Environment.Exit, the restart is aborted and the application just quits without trying to restart.

How can I get around this?

A bit more info:

My main class instantiates a subclass. This subclass calls Application.Restart if certain criteria are met. This causes .Net to call the FormClosed event on the main class. This event calls Environment.Exit to make sure all processes are closed when the user quits the application, which causes the restart to be aborted.

At a guess something in your code is preventing your application from properly closing prior to restarting, so make sure you check your code (ie FormClosed). Try starting a new process using the executable path, then closing the original.

System.Diagnostics.Process.Start(Application.ExecutablePath);
Application.Exit();

Hope it helps..!

Edit:

Why is Application.Restart() not reliable?

This should help, so possible dup!

Environment.Exit(0) is the API equivalent of ExitProcess(0) in kernel32.dll. It terminates the process immediately. Both Application.Exit and Application.Restart can hang while the main thread is processing.

For your case I suggest using Environment.Exit and start a new instance before that:

System.Diagnostics.Process.Start(Application.ExecutablePath);
Environment.Exit(0)

This will definitely exit your application.

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