Is it right to say that the non-Async method that drops the task is at the "top" of the asynchronous wait chain?

I understand how the method itself works async: the compiler converts it to code that creates a state machine (on the heap) so that this method acts "suspended" when it reaches the value of awaita Taskand the call stack is disabled. At the bottom of this chain is a method that simply returns a task, usually after starting a "naturally asynchronous" process, such as I / O.

Then what is at the “top”? I think the topmost method just discards the task so that it can move on. It's right?

Perhaps the easiest way to describe this is if our execution context is a Windows Forms application, and "top" is a message pump.

+4
source share
1 answer

Usually nothing is upstairs. The whole point of the state machine that you describe is that when the async action completes, it makes a callback to the state machine method MoveNext(the name is a legacy of the operator yield, which is essentially a primitive predecessor of asyncsemantics). This process is not actually call-based, it is more like an event making a callback for your method (in this case, the method MoveNextcreated by the compiler).

, , "". , "". , . MoveNext, - "".

:

static async void Main()
{
    Console.WriteLine(await A());
}

static async Task<int> A()
{
    return await B();
}

static async Task<int> B() 
{
    await Task.Delay(1);
    return 1;
}

Main? Main async, , . , async -. # 7.1 async.

, Main A? A B. B . async, callstack . B A. A Main. , Main, A, 1 .

+3

Source: https://habr.com/ru/post/1690535/


All Articles