假设我将这两个方法排入 for
循环
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);
});
}
有没有一种方法可以停止所有输出 Console.WriteLine("Output2");
的线程,但让那些运行该输出的线程 Console.WriteLine("Output");
?
最佳答案
您可以使用 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();
关于c# - 停止使用 ThreadPool.QueueUserWorkItem 创建的具有特定任务的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13590154/