首页 > 解决方案 > 从 Task.Run() 冒泡异常

问题描述

我有下面的代码,我试图找出来自 testFunction() 的异常。当我尝试运行代码时,没有抛出异常。

testFunction 是我想定期调用的任务

但是,如果我明确添加 throw new CustomException(); 在 Task.Run 中,代码正确抛出。我无法理解这种行为。我不能等待或等待 Task.Run 因为我希望 task.Run 自己独立运行,因此我使用 ContinueWith 但 continueWith 没有捕获异常,因此不会抛出它。请告知我在这里缺少什么?

public class Example
{

   public static CancellationTokenSource source = new CancellationTokenSource();
   public static void Main()
   {
       Console.WriteLine("Hello start");
       Task.Run(async () => 
       {

           while(token.IsCancellationRequested)
           {
               token.ThrowIfCancellationRequested();
               await testFunction(source.Token); 
               await Task.Delay(1000,token);                   
           }
                       
       } ).ContinueWith((t) =>
                        {                                
                           if (t.Exception != null) throw t.Exception;
                        });
   }
      
   public static async Task testFunction(CancellationToken token)
   {
       throw new CustomException();

   }
}

标签: c#asynchronousasync-awaittask

解决方案


我不能等待或等待 Task.Run 因为我希望 task.Run 自己独立运行

您必须使用await来观察异常。不过,您不必立即使用await。如果需要,您可以将其保存Task在变量中,await稍后再保存。

因此我正在使用 ContinueWith

ContinueWith不会做任何async/await不能做的事情。ContinueWith不会帮你的。它实际上应该几乎从不使用

我正在尝试消除来自 testFunction() 的异常。

让我转过头来:异常在哪里它在哪里冒泡?代码的哪一部分将观察到该异常?一旦你回答了这个问题,你就会找到把你的await.


推荐阅读