Cancel Threads

I have an application that uses 20 threads. This is an email client that uses streams to send mail.

Currently, threads are created in the main thread. But I wonder what if I want to cancel the whole operation? The only way to see this is to kill the main thread ... thus ending the program.

Should I create a stream that encapsulates streams for distribution so that I can kill the encapsulating stream?

I am currently using BackgroundWorker and this is a WF application.

+3
source share
1 answer

BackgroundWorker, , . WorkerSupportsCancellation true BackgroundWorker CancelAsync, .

, , . , CancellationPending BackgroundWorker.

MSDN .


. BackgroundWorker 20 ; a BackgroundWorker . 20 BackgroundWorkers? , , ? concurrency Winforms, .

, ManualResetEvent. , . :

ManualResetEvent cancelEvent = new ManualResetEvent(false);
for (int i = 0; i < 20; i++)
{
    ThreadPool.QueueUserWorkItem(s =>
    {
        // Do some work
        if (cancelEvent.WaitOne(0, true))
            return;
        // Do some more work
        // etc.
    });
}

- , cancelEvent.Set(), , .

+3

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


All Articles