Application.Exit () vs Application.ExitThread () vs Environment.Exit ()

I am trying to figure out what I should use. When my WinForm application closes, Form in Dialog mode is triggered. In this form, a background worker works, which synchronizes the database with the remote database and displays its progress in a โ€œburst formโ€.

I have a way like this:

private void CloseMyApp() { SaveUserSettings(); splashForm = new SplashForm(); splashForm.ShowDialog(); Application.ExitThread(); //Application.Exit(); } 

which I call to close my application from Menu โ†’ Exit and in the Form_FormClosing() event. Application.Exit() gives the following error ->

The collection has been modified; enumeration operation cannot be performed.

Now I read that Environment.Exit() is cruel and means that maybe something is wrong with your application (see here ).

Application.ExitThread() works, but I am convinced that it can only be APPEARING working, and since I have never used it before, I am not sure when this is usually suitable for this.

+31
multithreading c # winforms exit
Aug 21 '09 at 16:10
source share
2 answers

Unfortunately, the problem is not caused by any of them and really exists (even if you do not receive the message) in all these scenarios.

Your problem is this:

When I close my WinForm application, the form mode starts in dialog mode. This form launches a background worker, which synchronizes the database with the remote database and displays its progress in the โ€œBurst Formโ€.

Since you do not close the panel when you request shutdown, all the Exit functions try to tear down the background stream. Unfortunately, this probably happens in the middle of your DB synchronization, and an enumeration that works in the save logic probably provides this error.

I would recommend not using any of them - just call myMainForm.Close() . This should close your main form, which will eliminate your closure logic accordingly. Once the main form of the application closes, it will be gracefully closed.

+24
Aug 21 '09 at 16:51
source share

Environment.Exit() used for console applications.

Do you want to use: System.Windows.Forms.Application.Exit()

By retrieving a thread, you exit the context of the current thread, leaving running running foreground threads. I suspect that the thread causing the error is still working, so you essentially masked the problem, rather than working around it. I would try to find out why you get this error "Collection was modified; enumeration operation may not execute." upon exit. It is exposed by Application.Exit() but not called by it.

+9
Aug 21 '09 at 16:16
source share



All Articles