Stop a Thread Politely

Problem

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

Solution

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

Discussion

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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.