Stop whole thread in .NET ThreadPool?

I use ThreadPool in .NET to make some web request in the background, and I want the Stop button to cancel all threads, even if they are in the middle of the request, so a simple bool will not do the job.

How can i do this?

+4
source share
3 answers

The proper way to handle this is to have the flag object that you are signaling.

Code running on these threads should periodically check this flag to see if it should exit.

For example, a ManualResetEvent object is suitable for this.

Then you can ask the threads to exit as follows:

evt.Set(); 

and inside the threads you check for it like this:

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

Secondly, since you use the thread pool, it happens that all the elements that you queued will be processed anyway, but if you add the if statement above to the very beginning of the thread method, it will exit immediately. If this is not enough, you should create your own system using regular threads, so you have full control.

Oh, and just to make sure you don't use Thread.Abort. Ask the threads to exit normally, do not kill them directly.

+4
source

Your situation is pretty much the canonical use case of the Cancel model in the .NET platform.

The idea is that you create a CancellationToken object and make it available for an operation that you can cancel. Your operation sometimes checks the property of the IsCancellationRequested token or calls ThrowIfCancellationRequested .

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

This undo model combines well with the .NET parallel task library and is quite lightweight, moreover, than using system objects such as ManualResetEvent (although this is a perfectly valid solution too).

+9
source

If you are going to stop / cancel something in another thread, ThreadPool not the best choice, you should use Thread instead and manage all of them in the container (for example, global List<Thread> ), which ensures that you have full control over all threads.

+2
source

Source: https://habr.com/ru/post/1340746/


All Articles