Krtti
Krtti

Reputation: 62

Exception is not being thrown, inside task.ContinueWith(), even when .Result is used

When running below program, I am getting output as But when I use getTask.Result outside continueWith, I am seeing exception instantly. I am following a pluralsight course, Instructor is getting exception, but it's behaving differently for me.

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);
}

Upvotes: 1

Views: 455

Answers (2)

usr
usr

Reputation: 171178

Likely, t.Result throws. This causes the continuation task to exit in a faulted state. This happens before there is console output.

Maybe you want:

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

Also, the program is racy due to the 10 seconds delay. I assume you are aware of that and have made sure that the URL responds in less time... If not, wait for the continuation task to complete e.g. Task.WhenAll(continuationTask).Wait().

Upvotes: 1

TheHvidsten
TheHvidsten

Reputation: 4418

Regular exceptions are not caught when they occur inside a task. You need to use AggregateException to catch exceptions occuring inside tasks.

Encapsulating your code in this should catch it and make you able to see what's wrong:

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

You can read more about it on MSDN

Upvotes: 0

Related Questions