C# 停止/取消正在运行的线程
在我的windows服务应用程序中,我启动了多个线程,如下所示:C# 停止/取消正在运行的线程,c#,multithreading,c#-4.0,C#,Multithreading,C# 4.0,在我的windows服务应用程序中,我启动了多个线程,如下所示: class ConsumingEnumerableDemo { // Demonstrates: // BlockingCollection<T>.Add() // BlockingCollection<T>.CompleteAdding() // BlockingCollection<T>.GetConsumingEnumerable
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);
}
}
}
}
类consumineGenumerableDemo
{
//表明:
//BlockingCollection.Add()
//BlockingCollection.CompleteAdding()
//BlockingCollection.GetConsumingEnumerable()
public static void BC_getconsumineGenumerable()
{
使用(BlockingCollection bc=new BlockingCollection())
{
//开始制作任务
Task.Factory.StartNew(()=>
{
对于(int i=0;i<10;i++)
{
bc.添加(i);
Thread.Sleep(100);//添加之间睡眠100毫秒
}
//需要这样做才能防止下面的foreach被吊死
完成添加();
});
//现在使用foreach使用阻塞集合。
//使用bc.GetConsumingEnumerable()而不仅仅是bc,因为
//前者将阻止等待完工,后者将阻止等待完工
//只需拍摄基础集合当前状态的快照。
foreach(bc.GetConsumingEnumerable()中的变量项)
{
控制台写入线(项目);
}
}
}
}
如果我想停止这些任务,怎么做?
我听说过“取消代币”,但不知道如何将其应用到案例中。只需定义一个
然后像这样使用它:
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);
此外,您可能还想看看这些博客帖子:
看看如果你这样做,你要么把
completedadding
放在finally
块中,要么从其他地方调用completedadding
。否则,消费者将无限期地阻塞。
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);
cts.Cancel();