O'Reilly logo

Microsoft® Visual Basic® .NET Programmer's Cookbook by Matthew MacDonald

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required