Multi-Threading - a cleaning strategy at the end of the program

What is the best way to end a multithreaded application in its purest form? I start several socket connections from the main thread on separate sockets and wait for the end of my work day in the main thread and use it now System.Environment.Exit(0)to complete it.

This results in an unhandled exception in one of the child elements. Should I stop streams from the list? I did not want to realize any real stops in children, so I wonder about the best practice. Sockets are fully decorated with proper destructors to exit the system and close, but still lead to errors.

+5
source share
3 answers

For manually created threads, you must set the IsBackground property to true. In this case (if all your threads except the main one) will be the background, the application will be gracefully closed after returning from Main (string [] arg).

PS All threads threads are the background.

+2
source

check out jon skeet articles on multithreading:

http://www.yoda.arachsys.com/csharp/threads/

especially "Disabling workflows gracefully":

http://www.yoda.arachsys.com/csharp/threads/shutdown.shtml

+4
source

, (, ), Begin/End . ManualResetEvent " ". AsyncWaitHandle . .

Example:

// exit is a ManualResetEvent
var asyncResult = socket.BeginAccept(null, null);
if(WaitHandle.WaitAny(new[] { exit, asyncResult.AsyncWaitHandle }) == 0)
   return;
var connection = socket.EndAccept(asyncResult);

And in your main method, when you want to exit:

exit.Set();
0
source

All Articles