码迷,mamicode.com
首页 > Web开发 > 详细

How to cancel parallel loops in .NET C# z

时间:2014-05-22 16:43:14      阅读:332      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   c   code   java   

bubuko.com,布布扣
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

Task.Factory.StartNew(() =>
{
    Thread.Sleep(5000);
    cancellationTokenSource.Cancel();
    Console.WriteLine("Token cancelled");
});

ParallelOptions parallelLoopOptions =
    new ParallelOptions()
    {
        CancellationToken = cancellationTokenSource.Token
    };


try
{               
    Parallel.For(0, Int64.MaxValue, parallelLoopOptions, index =>
    {
        double result = Math.Pow(index, 3);
        Console.WriteLine("Index {0}, result {1}", index, result);
        Thread.Sleep(100);
    });
}
catch (OperationCanceledException)
{
    Console.WriteLine("Cancellation exception caught!");
}
bubuko.com,布布扣

 

How to cancel parallel loops in .NET C# z,布布扣,bubuko.com

How to cancel parallel loops in .NET C# z

标签:style   class   blog   c   code   java   

原文地址:http://www.cnblogs.com/zeroone/p/3744057.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!