0

If an async method declared with async has a return type of Task or Task<TResult> it can be awaited. Inside the method no task is returned in C# code, but in case of Task<TResult> a value of TResult. For instance:

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

The resulting IL code returns the task of the AsyncTaskMethodBuilder that started the compiled state machine. My question is what this task actually represents. I assume it's a task that represents not a thread or so, but the execution of the state machine. I assume also that the task is completed when the state machine is finished or set to the Faulted state when an Exception occurs. I appreciate clarification.


1 답변


2

The task conceptually represents the method.

When the method returns, the task is completed (successfully), with the result set to the value returned by the method (if applicable). If the method throws an exception, the task is faulted (completed with an error). There's a special case for OperationCanceledException: in that case, the task is canceled (completed with cancellation).

Technically, the task does represent the state machine, which is a rewriting of the method. But since the state machine is hidden, the task conceptually represents the method itself.


Related

Latest