Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread does not abort on application closing

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.

like image 829
migajek Avatar asked May 17 '10 21:05

migajek


1 Answers

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.

like image 58
Mark Byers Avatar answered Sep 21 '22 12:09

Mark Byers