簡體   English   中英

如何從已取消的任務中獲取內部異常?

[英]How to get the inner exception from a cancelled task?

我有一個在發生異常的情況下取消使用sme取消令牌的任務並引發異常的任務:

var cancellationTokenSource = new CancellationTokenSource();

var task1 = Task.Factory.StartNew(
                () =>
                    {
                        try
                        {
                            // Do work 
                        }
                        catch (Exception exception)
                        {                              
                            cancellationTokenSource.Cancel();

                            // rethrow the error
                            throw;
                        }     
                    },
                cancellationTokenSource.Token,
                TaskCreationOptions.None,
                taskScheduler); 

我還有另一個task3(返回任務),它是task1和task2的延續,並且使用相同的取消標記:

return task3 =
                Task.Factory.ContinueWhenAll(
                    new[] { task1, task2 },
                    tasks =>
                        {                           
                           // Do work
                        },
                cancellationTokenSource.Token,
                TaskContinuationOptions.None,
                this.taskScheduler).Unwrap();

一旦task1被取消,所有具有相同取消令牌的任務也將被取消。 我需要獲取task1引發的內部異常,該怎么辦?

如何使用異步/等待以及常規異常處理? 但是它將需要.NET 4.5。 這樣的事情(我不知道任務之間必須如何交互,因此您的代碼最終看起來可能會完全不同):

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication1
{

    class Program
    {
        static void Main(string[] args)
        {
            new MyClass().RunAsyncMethods();
            Console.ReadLine();

        }

        public class MyClass
        {
            public async void RunAsyncMethods()
            {
                try
                {
                    var cancellationTokenSource = new CancellationTokenSource();

                    var task1 = RunFirstTaskAsync(cancellationTokenSource);
                    var task2 = RunSecondTaskAsync(cancellationTokenSource);

                    await Task.WhenAll(task1, task2);
                    await RunThirdTaskAsync(cancellationTokenSource);
                    Console.WriteLine("Done");
                }
                catch (Exception exc)
                {
                    Console.WriteLine(exc.Message);
                }
            }

            public Task RunFirstTaskAsync(CancellationTokenSource cancelSource)
            {
                return Task.Run(() =>
                {
                    try
                    {
                        Console.WriteLine("First Task is Running");
                        throw new Exception("Error happened in first task");
                    }
                    catch (Exception exception)
                    {
                        cancelSource.Cancel();

                        throw;
                    }
                },
                    cancelSource.Token);
            }

            public Task RunSecondTaskAsync(CancellationTokenSource cancelSource)
            {
                return Task.Run(
                    () =>
                    {
                        Console.WriteLine("Second Task is Running");
                    },
                    cancelSource.Token);
            }

            public Task RunThirdTaskAsync(CancellationTokenSource cancelSource)
            {
                return Task.Run(
                    () =>
                    {
                        Console.WriteLine("Third Task is Running");
                    },
                    cancelSource.Token);
            }
        }
    }
}

更新:我更新了代碼以使用WhenAll。

更新:更新了代碼以使用Task.Run方法創建任務,而不是使用冷任務。

更新:您可以省略異步/等待(盡管我認為這樣更好),並進行一些老式的TPL錯誤處理。 根本不對任務3(返回任務)使用取消令牌,而僅對它正在等待的任務使用取消令牌。 當它們完成時(正常或通過異常/取消),您可以像下面這樣處理task3中的異常:

// don't use the cancellation token for the third task as you used for the previous ones
var task3 = Task.Factory.ContinueWhenAll(
                    new[] { task1, task2 },
                    tasks =>
                    {
                        if (tasks[0].Exception != null)
                        {
                            tasks[0].Exception.Handle(exc =>
                            {
                                Console.WriteLine("First task failed :(");
                                return false; // signal that exception was handled, so it won't propagate
                            });
                            // add additional code here, or inside the Handle method above
                        }

                        if (tasks[1].Exception != null)
                        {
                            tasks[1].Exception.Handle(exc =>
                            {
                                Console.WriteLine("Second task failed :(");
                                return false; // signal that exception was handled, so it won't propagate
                            });
                            // add additional code here, or inside the Handle method above
                        }

                        // do the same for the rest of the tasks or iterate throught them with a foreach loop...
                    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM