溫馨提示×

如何處理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
            {
                // 在此處執(zhí)行可能引發(fā)異常的操作
                if (number == 3)
                {
                    throw new InvalidOperationException("模擬異常");
                }
                Console.WriteLine($"處理數(shù)字: {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
            {
                // 在此處執(zhí)行可能引發(fā)異常的操作
                if (number == 3)
                {
                    throw new InvalidOperationException("模擬異常");
                }
                Console.WriteLine($"處理數(shù)字: {number}");
            }
            catch (Exception ex)
            {
                // 將異常添加到AggregateException中
                aggregateException = new AggregateException(ex);
            }
        });

        // 檢查是否有異常
        if (aggregateException != null)
        {
            // 如果有異常,則重新拋出AggregateException
            throw aggregateException;
        }

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

這兩種方法都可以有效地處理Parallel.ForEach中的異常。第一種方法在每個并行任務(wù)中使用try-catch塊捕獲異常,而第二種方法使用AggregateException收集所有并行任務(wù)中的異常。根據(jù)您的需求和編程風(fēng)格選擇合適的方法。

0