停止/取消运行线程 [英] Stop/Cancel running threads
本文介绍了停止/取消运行线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的Windows服务应用程序中,我开始多个线程:
In my windows service application, I started multiple threads as:
class ConsumingEnumerableDemo
{
// Demonstrates:
// BlockingCollection<T>.Add()
// BlockingCollection<T>.CompleteAdding()
// BlockingCollection<T>.GetConsumingEnumerable()
public static void BC_GetConsumingEnumerable()
{
using (BlockingCollection<int> bc = new BlockingCollection<int>())
{
// Kick off a producer task
Task.Factory.StartNew(() =>
{
for (int i = 0; i < 10; i++)
{
bc.Add(i);
Thread.Sleep(100); // sleep 100 ms between adds
}
// Need to do this to keep foreach below from hanging
bc.CompleteAdding();
});
// Now consume the blocking collection with foreach.
// Use bc.GetConsumingEnumerable() instead of just bc because the
// former will block waiting for completion and the latter will
// simply take a snapshot of the current state of the underlying collection.
foreach (var item in bc.GetConsumingEnumerable())
{
Console.WriteLine(item);
}
}
}
}
我想停止任务,怎么样?
我听说取消令牌,但不知道如何应用它。
If I want to stop the tasks, how? I heard about "Cancellation Tokens" but not sure how to apply it to the case.
推荐答案
var cts = new CancellationTokenSource();
并使用如下:
Task.Factory.StartNew(() =>
{
for (int i = 0; i < 10; i++)
{
bc.Add(i);
Thread.Sleep(100); // sleep 100 ms between adds
cts.ThrowIfCancellationRequested();
}
// Need to do this to keep foreach below from hanging
bc.CompleteAdding();
},cts.Token);
当您要取消任务时,请使用:
When you want to cancel your task, use:
cts.Cancel();
另外,您可能需要查看这些博文:
Also you might want take a look at these blog posts:
- Parallel Programming: Task Cancellation
- Async in 4.5: Enabling Progress and Cancellation in Async APIs
这篇关于停止/取消运行线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文