Although the main thread finished, the process keeps running. What might be the cause? how can i prevent it?
-
Maybe the UI was handled on another thread? – James Johnson Aug 24 '11 at 18:15
-
There is no UI. I can't share any code, sorry – Erik Sapir Aug 24 '11 at 18:17
-
2You need to comment out line 5. – heisenberg Aug 24 '11 at 18:18
3 Answers
If you are calling Application.exit()
, that could be your problem. From MSDN:
This method stops all running message loops on all threads and closes all windows of the application. This method does not force the application to exit. The Exit method is typically called from within a message loop, and forces Run to return.
This function was named stupidly if you ask me. Probably should have been called StopMessageLoops
or something like that. Instead, use System.Environment.Exit()
-
@Erik well try putting `System.Environment.Exit(0);` wherever in your code you want the application to exit. That should do the trick. – Daniel Aug 24 '11 at 18:20
An application does not exit until all non-background threads have finished.
Things you can do:
Set some kind of signal when you want to exit so threads other than the main-thread can exit themselves.
Use background threads for threads that should be killed when the application exists.
Using Environment.Exit is a rather brutal way to make an application shut down and should be avoided if possible. The threads that keep the application from exiting might need to be properly shut down, e.g., to prevent data corruption.

- 213,145
- 36
- 401
- 431
Attach to the process with a debugger and look the threads that are remaining. The process will exit when all threads have exited.
You could try looping through the application thread list and terminating all the threads. This might have bad side effects though.

- 400
- 1
- 7