【问题标题】:Stop/Cancel running threads停止/取消正在运行的线程
【发布时间】:2014-01-09 22:16:12
【问题描述】:

在我的 Windows 服务应用程序中,我启动了多个线程:

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

如果我想停止任务,怎么办? 我听说过“取消令牌”,但不知道如何将其应用到案例中。

【问题讨论】:

标签: c# multithreading c#-4.0


【解决方案1】:

只需定义一个Cancellation Token Source

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

当你想取消你的任务时,使用:

cts.Cancel();

您可能还想看看这些博客文章:

  1. Parallel Programming: Task Cancellation
  2. Async in 4.5: Enabling Progress and Cancellation in Async APIs

【讨论】:

  • 如果你这样做,你要么必须将CompleteAdding 放在finally 块中,要么从其他地方调用CompleteAdding。否则消费者将无限期阻塞。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-21
相关资源
最近更新 更多