4

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..

4
  • 2
    This article had a good explanation: gamlor.info/wordpress/2010/10/… Commented Dec 7, 2013 at 13:33
  • Thanks for linking to the article. Commented Dec 7, 2013 at 13:50
  • wow! greate.. you saved my mind dude Commented Dec 7, 2013 at 13:51
  • 1
    @user2924454: I have an async intro on my blog that you may find helpful; I tried to make it an intro that covers everything you need to know in a single post, with detailed followup links at the bottom. Commented Dec 7, 2013 at 15:44

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Is a console app so it behaves like a user created thread would in a UI app.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.