ITPub博客

首页 > Linux操作系统 > Linux操作系统 > .NET4.0线程池的Cooperative Cancellation模式

.NET4.0线程池的Cooperative Cancellation模式

原创 Linux操作系统 作者:iDotNetSpace 时间:2010-03-01 11:00:45 0 删除 编辑
刚装了VS2010RC版,体验一下.NET4.0线程池新增的Cooperative Cancellation模式。

  用过.NET线程池的 人都知道,一旦把要执行的代码交给线程池去执行后,我们基本上就失去了代码在运行中的控制能力。比如,我们想在某个时刻取消这段代码的执行,就得另想一个 办法。随着.NET4.0到来,这个问题得到了解决。.NET4.0引入了一种新的设计模式---合作取消模式(Cooperative Cancellation)。

  .NET4.0的System.Threading命名空间下新增了两个成员,一个是CancellationTokenSource类,一个是CancellationToken结构。CancellationTokenSource类的主要成员如下:

代码
<!--Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->public sealed class CancellationTokenSource : IDisposable {
public CancellationTokenSource();
public void Dispose();
public Boolean IsCancellationRequested { get; }
public CancellationToken Token { get; }//CancellationToken结构
public void Cancel();
public void Cancel(Boolean throwOnFirstException);
}

  CancellationToken结构代码大致如下:

代码
<!--Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--> public struct CancellationToken
    { 
        
public Boolean IsCancellationRequested { get; }
        
public void ThrowIfCancellationRequested();
        
// 当CancellationTokenSource取消时使用的信号量
        public WaitHandle WaitHandle { get; }
        
public static CancellationToken None { get; }
        
public Boolean CanBeCanceled { get; }
        
public CancellationTokenRegistration Register(Action<Object> callback, Object state, Boolean useSynchronizationContext);
    }

  使用代码如下:

代码
<!--Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->using System;
using System.Threading;

namespace CooperativeCancellation
{
    
class Program
    {
        
static void Main(string[] args)
        {
            CancellationTokenSource cts 
= new CancellationTokenSource();
            ThreadPool.QueueUserWorkItem(o 
=> ExecuteInThreadPool(cts.Token));
            Console.WriteLine(
"Press  to cancel the operation.");
            Console.ReadLine();
            cts.Cancel();
            Console.ReadLine();
        }

        
static void ExecuteInThreadPool(CancellationToken token)
        {
            Console.WriteLine(
"Enter in ThreadPool.");
            
while (!token.IsCancellationRequested)
            {
                Console.Write(
" .");
                Thread.Sleep(
1000);
            }
            Console.WriteLine(
"Operation was be cancel.");
        }
    }
}

  代码简单,我在这里就不多说了。总之,有了Cooperative Cancellation模式后,我们对.NET线程池中的代码的执行有了更大的控制力度,真是个不错的功能。

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/12639172/viewspace-628253/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2008-01-04

  • 博文量
    2376
  • 访问量
    5765963