Parallel.For异常处理的问题

.Net技术 码拜 8年前 (2016-05-10) 1862次浏览
1、为什么打印不出10个报错的信息呢?
2、假如需要打印出10个报错信息 需要在代码上怎么做调整

    public class TestClass
    {
        private static readonly object locker = new object();
        public void Test(int Number)
        {
            lock (locker)
            {
                throw new Exception("123123");
            }
        }
    }
class Program
    {
        public static void Main()
        {
            try
            {
                Parallel.For(0, 10, (i) =>
                {
                    try
                    {
                        TestClass a = new TestClass();
                        a.Test(i);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                });
            }
            catch (AggregateException ex)
            {
                foreach (var single in ex.InnerExceptions)
                {
                    Console.WriteLine(single.Message);
                }
            }
            Console.ReadLine();
}
解决方案

20

                Parallel.For(0, 10, (i) =>
                {
                    try
                    {
                        TestClass a = new TestClass();
                        a.Test(i);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                        throw ex;
                    }
                });

80

在里面处理

Parallel.For(0, 10, (i) =>
{
    try
    {
        TestClass a = new TestClass();
        a.Test(i);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
});

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明Parallel.For异常处理的问题
喜欢 (0)
[1034331897@qq.com]
分享 (0)