Given the following code:
public static async Task TestTask()
{
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
await Task.Delay(1000);
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
}
We see that the current thread is changed after the await
. However, this code is not multi-threaded and instead it is meant to provide non-blocking IO (with reference to JavaScript's mechanism). But why does it happen? and since it happens, does it mean that anything that comes after the awaited
line must consider thread-safety (for example adding to a HashSet
) while that would not be needed before that awaited
line?