c# TPL AggregateException无法捕获任务中异常

private static void List_19_Basic_Exception_Handling()
    {
        Task task1 = new Task(() =>
        {
            for (int i = 0; i < 5; i++)
            {
                ArgumentOutOfRangeException exception = new ArgumentOutOfRangeException();
                exception.Source = "task1";
                throw exception;
                }
            });

        Task task2 = new Task(() =>
        {
            throw new NullReferenceException();
        });

        Task task3 = new Task(() =>
        {
            Console.WriteLine("Hello from Task 3");
        });



        task1.Start();
        task2.Start();
        task3.Start();

        try
        {
            Task.WaitAll(task1, task2, task3);
        }
        **catch (AggregateException ex) // 这里始终无法捕获异常,不知道为什么**
        {
            foreach (Exception inner in ex.InnerExceptions)
            {
                Console.WriteLine("Exception type {0} from {1}", inner.GetType(), inner.Source);
            }
        }
    }

static void Main(string[] args)
    {

         List_19_Basic_Exception_Handling();

        // wait for input before exiting
        Console.WriteLine("Main method complete. Press enter to finish.");
        Console.ReadLine();
    }

我是在VS2010中运行时出现这种问题,不知道为什么无法捕获导演,有知道原因大牛,欢迎留言,谢谢!:)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是一个简单的基于 TPLC# 应用程序示例,它使用 Parallel.ForEach 方法并行处理一个字符串列表: ```csharp using System; using System.Collections.Generic; using System.Threading.Tasks; class Program { static void Main(string[] args) { List<string> list = new List<string> { "apple", "banana", "cherry", "date", "elderberry", "fig", "grape" }; Parallel.ForEach(list, item => { Console.WriteLine($"Processing item '{item}' on thread {Task.CurrentId}"); // 模拟处理间 Task.Delay(1000).Wait(); }); Console.WriteLine("All items processed"); } } ``` 在上面的示例,我们首先创建了一个字符串列表 `list`,其包含七个元素。然后,我们使用 `Parallel.ForEach` 方法对列表的每个元素进行并行处理。在处理每个元素,我们将元素的名称和当前线程的 ID 打印到控制台上,并使用 `Task.Delay` 方法模拟处理间。最后,我们打印一条消息,表示所有元素都已处理完毕。 在运行上面的示例,您应该会看到类似于以下输出: ``` Processing item 'banana' on thread 3 Processing item 'apple' on thread 1 Processing item 'cherry' on thread 2 Processing item 'elderberry' on thread 4 Processing item 'fig' on thread 5 Processing item 'date' on thread 6 Processing item 'grape' on thread 7 All items processed ``` 可以看到,所有元素都在不同的线程上并行处理,处理间也得到了模拟。请注意,由于 `Parallel.ForEach` 方法是异步的,因此程序可能会在所有元素都处理完毕之前结束。如果您希望等待所有任务完成后再继续执行程序,请使用 `Task.WaitAll` 方法等待所有任务完成。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值