Reputation: 1942
i`v been studing about async progrmaming in .net today and what i understood is that this code Should NOT create a new thread but i see different ThreadId with calling Thread.CurrentThread.ManagedThreadId.
static void Main(string[] args)
{
Do();
Console.WriteLine("Main {0}",Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(400);
}
private static async void Do()
{
Task<string> task = new StreamReader(@"D:\a.txt").ReadLineAsync();
string result = await task;
Console.WriteLine("DO {0}", Thread.CurrentThread.ManagedThreadId);
}
thanks everyone for reading this..
Upvotes: 4
Views: 118
Reputation: 5390
The reason your getting different thread ids is that you have created a console app. On a UI app there is a special SynchronizationContext
saying that the callbacks should be on the UI thread. Console apps don't have this synchronization context as the console methods are thread safe so don.t need to be called on the main thread. This means that an async call on the the main thread behaves the same as on any user created threads would which is to fire callbacks to the thread pool as your seeing.
Upvotes: 4