任务内部未引发异常.ContinueWith(),即使 .使用结果



在程序下面运行时,我得到的输出为但是当我在 getTask.Result 外面继续时,我立即看到了异常。我正在遵循多元化课程,讲师正在获得例外,但它对我来说表现不同。

Going to start work
Setting up continuation
Continuing with main method
Press any key to continue . . .

static void Main(string[] args)
{            
  var web = new WebClient();            
  Console.WriteLine( "Going to start work");
  //slowmissing has a process request where statuscode is set to 404
  Task<string> getTask=  web.DownloadStringTaskAsync("http://localhost:49182/SlowMissing.ashx");
   Console.WriteLine(  "Setting up continuation");
   getTask.ContinueWith((t) =>
   { 
      Console.WriteLine(t.Result); 
   });
   Console.WriteLine( "Continuing with main method");
   Thread.Sleep(10000);
}

很可能,t.Result投掷。这会导致继续任务以故障状态退出。这发生在控制台输出之前。

也许你想要:

Console.WriteLine(t.Status);
Console.WriteLine(t.Exception);

此外,由于 10 秒的延迟,该程序很不雅。我假设您知道这一点,并确保 URL 在更短的时间内响应......如果没有,请等待继续任务完成,例如 Task.WhenAll(continuationTask).Wait() .

当常规异常发生在任务中时,不会捕获常规异常。您需要使用 AggregateException 来捕获任务中发生的异常。

将你的代码封装在这个应该会抓住它,让你能够看到哪里出了问题:

try {
    // Your code here
} catch (AggregateException ex) {
    // The actual exception is included in ex.InnerException
}

您可以在 MSDN 上阅读有关它的更多信息

最新更新