当异常发生时,如何在pararell foreach循环中停止任务?

时间:2017-05-25 08:35:15

标签: c# task parallel.foreach cancellation cancellationtokensource

我需要知道在异常发生时如何在pararell foreach循环中停止任务?如果Foo1()抛出异常,则应取消DoSomeWork()。

项目类

class Item
 {
     public async Task DoSomeWork()
            {
                try
                {
                     await Foo1();
                     await Foo2();
                }
                catch (Exception ex)
                {
                    Console.Writeline(ex.Message);
                }
             }


    private async Task Foo1()
    {   
        try
        {
        //
        // some functionality
        //
        }
        catch(Exception ex)
        {
            // If exception occurs, then how cancel Task DoSomeWork()
        }
    }

    private async Task Foo2()
    {   
        try
        {
        //
        // some functionality
        //
        }
        catch(Exception ex)
        {
            // If exception occurs, then how cancel Task DoSomeWork()
        }
    }
}

和Paracll.Foreach循环的ItemCollection类

class ItemCollection
{
     public void StartAsync()
        {
            try
            {
                IList<Task> il = new List<Task>();
                Parallel.ForEach(ListOfItems, t => il.Add(t.DoSomeWork()));
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message); 
            }
        }
}

如何在此示例中使用CancellationToken属性?

1 个答案:

答案 0 :(得分:0)

以下是MSDN的一个很好的例子:https://msdn.microsoft.com/de-de/library/ee256691(v=vs.110).aspx

在循环开始之前:

CancellationTokenSource cts = new CancellationTokenSource();
ParallelOptions po = new ParallelOptions();
po.CancellationToken = cts.Token;

循环内部:

Parallel.ForEach(nums, po, (num) =>
                {
                    // Do some work here
                    po.CancellationToken.ThrowIfCancellationRequested();
                });

从另一个主题,您可以触发取消事件:

cts.Cancel();