停止/取消运行线程 [英] Stop/Cancel running threads

查看:231
本文介绍了停止/取消运行线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的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:


  1. 并行规划:任务取消

  2. 4.5中的异步:在Async API中启用进度和取消

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

这篇关于停止/取消运行线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆