I was going through https://blog.stephencleary.com/2012/02/async-and-await.html and according to the author the Context
is either of the following:
If you’re on a UI thread, then it’s a UI context.
If you’re responding to an ASP.NET request, then it’s an ASP.NET request context.
Otherwise, it’s usually a thread pool context.
So in a console application with the following code:
public static void Main()
{
Thread.CurrentThread.Name = "MainThread";
var task = SomeAsync();
string result = task.Result;
Console.WriteLine(result);
}
private static async Task<string> SomeAsync() {
await Task.Delay(2000);
return "random String";
}
Here we start an async method from the Main
method. The execution of this async method will take 2 seconds and by the time it completes the control will be back in the Main
method at the line where we are blocking on the result of the async method. So we can say that the MainThread
is blocked waiting for the result of SomeAsync
. By the time SomeAsync
completes, the MainThread
is still blocked.
So can I say that the continuation of the async method will be executed on a different thread from the thread pool (as this code works and prints the string correctly)? Had it been a UI application it would have resulted in a deadlock but no deadlock in case of console application. Are the console applications contextless and may use a new thread from the thread pool when the need arises?