Thread does not abort on application closing

migajek picture migajek · May 17, 2010 · Viewed 9.6k times · Source

I have an application which does some background task (network listening & reading) in a separate Thread. It seems however that the Thread is not being Terminated/Aborted when I close the application (click "x" button on titlebar). Is that because the main Thread routine is while(true) {...} ? What is the solution here? I was looking for some "interruption" flag for the Thread as the condition for "while" loop, but didn't found any.

Answer

Mark Byers picture Mark Byers · May 17, 2010

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.