在task.ContinueWith()中,即使使用.Result,也不会抛出异常

时间:2016-06-05 17:11:37

标签: c# asynchronous task-parallel-library

在程序下运行时,我输出为 但是当我在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);
}

2 个答案:

答案 0 :(得分:1)

可能,t.Result抛出。这会导致延续任务在故障状态下退出。这在控制台输出之前发生。

也许你想要:

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

此外,由于延迟10秒,节目很活泼。我假设您已经意识到这一点,并确保URL在更短的时间内响应...如果没有,请等待继续任务完成,例如Task.WhenAll(continuationTask).Wait()

答案 1 :(得分:0)

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

将代码封装在其中应该抓住它并让你能够看到错误:

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

You can read more about it on MSDN