加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – PLINQ异常

发布时间:2020-12-15 23:27:09 所属栏目:百科 来源:网络整理
导读:我正在使用PLINQ,代码如下: static void Main(string[] args) { var lt = new Listint() {1,2,3,4,5}; try { var nlt = lt.AsParallel().Select(Test).ToList(); } catch (AggregateException e) { foreach (var ex in e.InnerExceptions) { Console.WriteL
我正在使用PLINQ,代码如下:

static void Main(string[] args)
    {
        var lt = new List<int>() {1,2,3,4,5};
        try
        {
            var nlt = lt.AsParallel().Select(Test).ToList();
        }
        catch (AggregateException e)
        {
            foreach (var ex in e.InnerExceptions)
            {
                Console.WriteLine(ex.Message);
            }
        }

    }

    private static bool Test(int n)
    {
        if (n == 1)
        {
            Thread.Sleep(1000);
        }
        if (n == 3)
        {
            Thread.Sleep(3000);
        }
        if (n == 5)
        {
            Thread.Sleep(5000);
        }
        if (n == 2 || n == 4)
        {
            throw new Exception("New exception");
        }
        Console.WriteLine("element : {0}",n);
        return true;
    }

结果是在5s之后总是抛出aggregateException(直到最后一个线程完成).似乎如果某些线程抛出异常,该线程的其余部分仍将继续运行.完成最后一个线程后,框架会聚合所有异常并将它们包装在aggregateException中.

是框架行为,如果10个线程中有3个抛出异常,它将等待其余7个线程完成并在最后抛出aggreagteException.

但是,当我遇到这个文件时:
https://msdn.microsoft.com/en-us/library/dd460712(v=vs.110).aspx

the query cannot continue after the exception is thrown. By the time your application code catches the exception,PLINQ has already stopped the query on all threads.

我想知道为什么我的代码不会以这种方式运行?如果在抛出异常后查询无法继续,则不会永远不会打印元素1,5,因为异常将已经抛出.

解决方法

从您提供的链接:

When exceptions are allowed to bubble up back to the joining thread,then it is possible that a query may continue to process some items after the exception is raised.

阿尔巴哈里的This section文章更好地解释了发生的事情:

Both PLINQ and the Parallel class end the query or loop execution upon encountering the first exception — by not processing any further elements or loop bodies. More exceptions might be thrown,however,before the current cycle is complete. The first exception in AggregateException is visible in the InnerException property.

抛出异常时,将不再处理集合中的更多值.但是,在抛出异常时,已经为所有5个int调用了方法Test(int).在这种情况下,PLINQ将等待这些方法调用(当前循环),并在完成所有调用后抛出AggregateException.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读