1

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.

TheHvidsten
  • 4,028
  • 3
  • 29
  • 62

2 Answers2

1

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!

Community
  • 1
  • 1
horHAY
  • 788
  • 2
  • 10
  • 23
1

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.

bytecode77
  • 14,163
  • 30
  • 110
  • 141
  • I added a flag that indicated whether it is a software restart or not and checked for that flag around the Process.Start in your example. This made it so that the processes were stopped. However, my application starts a bit too quickly so when it checks for already existing processes the other process hasn't finished quitting yet. I resolved this by adding a simple Thread.Sleep before checking for other processes. – TheHvidsten Apr 07 '15 at 11:53