Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop Threads created with ThreadPool.QueueUserWorkItem that have a specific task

Let's say I queue those two methods in a for loop

for (int i = 0; i < 100; i++)
{
    ThreadPool.QueueUserWorkItem(s =>
    {
        Console.WriteLine("Output");
        Thread.Sleep(1000);
    });
}

for (int i = 0; i < 100; i++)
{
    ThreadPool.QueueUserWorkItem(s =>
    {
        Console.WriteLine("Output2");
        Thread.Sleep(1000);
    });
}

Is there a way to stop all the threads that output Console.WriteLine("Output2"); but keep the ones running that output Console.WriteLine("Output"); ?

like image 579
maddo7 Avatar asked Nov 27 '12 17:11

maddo7


1 Answers

You could use a CancellationToken:

for (int i = 0; i < 100; i++)
{
    ThreadPool.QueueUserWorkItem(s =>
    {
        Console.WriteLine("Output");
        Thread.Sleep(1000);
    });
}

CancellationTokenSource cts = new CancellationTokenSource();

for (int i = 0; i < 100; i++)
{
    ThreadPool.QueueUserWorkItem(s =>
    {
        CancellationToken token = (CancellationToken) s;
        if (token.IsCancellationRequested)
            return;
        Console.WriteLine("Output2");
        token.WaitHandle.WaitOne(1000);
    }, cts.Token);
}

cts.Cancel();
like image 171
jaket Avatar answered Sep 21 '22 09:09

jaket