温馨提示×

如何处理C# Parallel.ForEach的异常

c#
小樊
81
2024-10-09 12:39:44
栏目: 编程语言

在C#中,使用Parallel.ForEach时处理异常的常见方法是使用ParallelLoopResultAggregateException

  1. 使用try-catch块捕获AggregateException:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

class Program
{
    static void Main()
    {
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };

        ParallelLoopResult result = Parallel.ForEach(numbers, number =>
        {
            try
            {
                // 在此处执行可能引发异常的操作
                if (number == 3)
                {
                    throw new InvalidOperationException("模拟异常");
                }
                Console.WriteLine($"处理数字: {number}");
            }
            catch (Exception ex)
            {
                // 在这里处理异常,例如将其记录到日志中
                Console.WriteLine($"捕获到异常: {ex.Message}");
            }
        });

        Console.WriteLine("完成");
    }
}
  1. 使用ParallelLoopResult.GetResults()AggregateException处理异常:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

class Program
{
    static void Main()
    {
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
        AggregateException aggregateException = null;

        ParallelLoopResult result = Parallel.ForEach(numbers, number =>
        {
            try
            {
                // 在此处执行可能引发异常的操作
                if (number == 3)
                {
                    throw new InvalidOperationException("模拟异常");
                }
                Console.WriteLine($"处理数字: {number}");
            }
            catch (Exception ex)
            {
                // 将异常添加到AggregateException中
                aggregateException = new AggregateException(ex);
            }
        });

        // 检查是否有异常
        if (aggregateException != null)
        {
            // 如果有异常,则重新抛出AggregateException
            throw aggregateException;
        }

        Console.WriteLine("完成");
    }
}

这两种方法都可以有效地处理Parallel.ForEach中的异常。第一种方法在每个并行任务中使用try-catch块捕获异常,而第二种方法使用AggregateException收集所有并行任务中的异常。根据您的需求和编程风格选择合适的方法。

0