I was trying to understand a bit about which threads things get run on. My understanding was, when we use await, the original context is captured and the continuation will run on the original thread. This not proving to me the case for me, see below code.
Is this because I am using .NET 6 and context don't matter in .NET Core/.NET 6 anymore? (EDIT: I was running this as console app)
await DoSomething();
public async Task DoSomething()
{
Console.WriteLine("Starting thread: " +Thread.CurrentThread.ManagedThreadId);
var listofProcessor = new List<Processor> {
new ("Processor"), new ("Processor1")
};
try
{
var tasks = listofProcessor.Select(x => x.Process());
Console.WriteLine($"Before Task.WhenAll {Thread.CurrentThread.ManagedThreadId}");
await Task.WhenAll(tasks);
Console.WriteLine($"After Task.WhenAll {Thread.CurrentThread.ManagedThreadId}");
}
catch (Exception e)
{
Console.WriteLine("Exception caught");
}
}
public class Processor
{
private string _name;
public Processor(string name) => _name = name;
public async Task<string> Process()
{
Console.WriteLine($"{_name}.BeforeAwait {Thread.CurrentThread.ManagedThreadId}");
await Task.Delay(100);
Console.WriteLine($"{_name}.AfterAwait {Thread.CurrentThread.ManagedThreadId}");
return "hellow";
}
}
I would expect, Console.WriteLine($"After Task.WhenAll xxx)
to be run on the original thread. But that is not happening. The result is:
Starting thread: 1
Before Task.WhenAll 1
Processor.BeforeAwait 1
Processor1.BeforeAwait 1
Processor.AfterAwait 9
Processor1.AfterAwait 6
After Task.WhenAll 6