In C # 5.0, the async / await function always starts in the main thread at the start of a run

I find that when I call the async function, the stream is the main stream first. When he meets the waiting task, the flow will be changed to another.

static void Main(string[] args)
{
    println("Mainthread ID " + Thread.CurrentThread.GetHashCode());
    var s = DoSomethingAsync();
    println("Waiting for DoSomethingAsync Complete ");
    Thread.Sleep(2000);
    println(s.Result.ToString());
}

static async Task<int> DoSomethingAsync()
{
    println("DoSomethingAsync Thread ID " + Thread.CurrentThread.GetHashCode());
    int val = await Task.Factory.StartNew(() =>
    {
        Thread.Sleep(1000);
        println("Task Thread ID " + Thread.CurrentThread.GetHashCode());
        return 100;
    });

    println("DoSomethingAsync end " + Thread.CurrentThread.GetHashCode());
    return val;

}

And the result is as follows:

11:40:34 383 Mainthread ID 1
11:40:34 398 DoSomethingAsync Thread ID 1
11:40:34 400 Waiting for DoSomethingAsync Complete
11:40:35 400 Task Thread ID 3
11:40:35 400 DoSomethingAsync end 3
11:40:36 401 100

We see that the mainthread identifier is 1. DoSomethingAsync Thread ID is also 1. They are the same. Therefore, at the start of the async function, this is the main thread that executes this part.

This means that when the main thread matches the async function, it will be blocked to start anything until it encounters the Wait task. The async function does not make things asynchronous instantly. It is right?

, "async" "", "async" .

+4
2

, "async", , -, Task.The "async" . ?

, . async , await, . await , .

, ThreadPoolSynchronizationContext. , .

+3

, . , . , . .

await SyncrhonizationContext, , .

+1

All Articles