frikrishna frikrishna - 2 months ago 8
C# Question

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

usr usr
Answer

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().