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

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


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();


No, you can't do that. If you want to do something a long the lines then you must write some code to manage it. At the very basic level you need something like this:

object syncObject = new object();bool shouldOutput2 = true;ThreadPool.QueueUserWorkItem(s =>{    lock(syncObject)    {        if(!shouldOutput2)        {           return;        }    }    Console.WriteLine("Output2");    Thread.Sleep(1000);});

Once you queue the items, then you can set the flag in order to tell the remaining items not to execute:

   lock(syncObject)   {        shouldOutput2 = false;   }

This is a very dirty way of doing it, but it seems like the only way given your example. If you can tell us more about what is the actual real-world behavior you're trying to accomplish, then there could be some better options.