Stop a Thread Politely


You want to stop a thread, but allow it to clean up the current task and end on its own terms.


Create a Boolean StopRequested flag that the threaded code can poll periodically.


When you use the Abort method to stop a thread, a ThreadAbortException is raised to the code that is currently running. The thread can handle this exception with code in a Catch or Finally block, but the exception cannot be suppressed. In other words, even if the exception is handled, it will be rethrown when the code in the Catch and Finally blocks finishes, until the thread finally terminates.

The Abort method isn’t always appropriate. A less disruptive choice is to create a more considerate thread that checks for stop requests. ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.