Thread does not abort on application closing Thread does not abort on application closing multithreading multithreading

Thread does not abort on application closing


The simplest way is to set the IsBackground property of the thread to true. This will prevent it from keeping the application open. An application terminates when all non-background threads terminate.

A more controlled way to stop the thread is to send it a message to shut down cleanly and ensure that it has terminated before letting your main thread terminate.

A method that I wouldn't recommend is to call Thread.Abort. This has a number of problems, one of which is that it is not guaranteed to terminate the thread. From the documentation:

Calling this method usually terminates the thread.

Emphasis mine.


You can always force the issue:

class Program{    public static void Main()    {        // ... do stuff        Environment.Exit(Environment.ExitCode);    }}

The better approach is to set the Thread.IsBackground property to true as Mark already mentioned.


You could improve the while(true) loop to

void DoWork() {    while(!ShouldIQuitManualResetEvent.WaitOne(0)) {      // do something    }    IDidQuitManualResetEvent.Set()}

A bit more graceful, short from the identifier names.