Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stopping all thread in .NET ThreadPool?

I am using ThreadPool in .NET to make some web request in the background, and I want to have a "Stop" button to cancel all the threads even if they are in the middle of making a request, so a simple bool wont do the job.

How can I do that?

like image 842
Meredith Avatar asked Feb 22 '11 06:02

Meredith


3 Answers

Your situation is pretty much the canonical use-case for the Cancellation model in the .NET framework.

The idea is that you create a CancellationToken object and make it available to the operation that you might want to cancel. Your operation occasionally checks the token's IsCancellationRequested property, or calls ThrowIfCancellationRequested.

You can create a CancellationToken, and request cancellation through it, by using the CancellationTokenSource class.

This cancellation model integrates nicely with the .NET Task Parallel Library, and is pretty lightweight, more so than using system objects such as ManualResetEvent (though that is a perfectly valid solution too).

like image 187
Wesley Hill Avatar answered Sep 30 '22 21:09

Wesley Hill


The correct way to handle this is to have a flag object that you signal.

The code running in those threads needs to check that flag periodically to see if it should exit.

For instance, a ManualResetEvent object is suitable for this.

You could then ask the threads to exit like this:

evt.Set();

and inside the threads you would check for it like this:

if (evt.WaitOne(0))
    return; // or otherwise exit the thread

Secondly, since you're using the thread pool, what happens is that all the items you've queued up will still be processed, but if you add the if-statement above to the very start of the thread method, it will exit immediately. If that is not good enough you should build your own system using normal threads, that way you have complete control.

Oh, and just to make sure, do not use Thread.Abort. Ask the threads to exit nicely, do not outright kill them.

like image 22
Lasse V. Karlsen Avatar answered Sep 30 '22 20:09

Lasse V. Karlsen


If you are going to stop/cancel something processing in another thread, ThreadPool is not the best choice, you should use Thread instead, and manage all of them in a container(e.g. a global List<Thread>), that guarantees you have full control of all the threads.

like image 21
Cheng Chen Avatar answered Sep 30 '22 19:09

Cheng Chen