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