Consider the following code:
static async Task ThrowException()
{
throw new Exception("exception 1");
Thread.Sleep(1000);
await Task.Delay(1000);
throw new Exception("exception 2");
}
static async Task Sleep()
{
Console.WriteLine("begin sleep");
Thread.Sleep(1000);
Console.WriteLine("end sleep");
Console.WriteLine("begin delay");
await Task.Delay(1000);
Console.WriteLine("end delay");
}
static async Task Main(string[] args)
{
{
Console.WriteLine("begin var task = Sleep();");
var task = Sleep();
Console.WriteLine("end var task = Sleep();");
Console.WriteLine("begin await task;");
await task;
Console.WriteLine("end await task;");
}
{
try
{
Console.WriteLine("begin var task = ThrowException();");
var task = ThrowException();
Console.WriteLine("end var task = ThrowException();");
Console.WriteLine("begin await task;");
await task;
Console.WriteLine("end await task;");
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
}
}
The result is following:
begin var task = Sleep();
begin sleep
end sleep
begin delay
end var task = Sleep();
begin await task;
end delay
end await task;
begin var task = ThrowException();
end var task = ThrowException();
begin await task;
exception 1
My question is that why exception 1
appears after "begin await task" task but "end sleep" appears before "begin await task"? I think it does not start a new thread before await Task.Delay()
, it should happen in the same thread like Thread.Sleep()
, so I expect the "exception 1" throw immediately before "end var task = ThrowException();"