Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call chain for async/await ... await the awaitable or return the awaitable?

Given an async method:

public async Task<int> InnerAsync()
{
    await Task.Delay(1000);
    return 123;
}

And calling it through an intermediate method, should the intermediate method await the async method IntermediateA or merely return the Task IntermediateB?

public async Task<int> IntermediateA()
{
    return await InnerAsync();
}

private Task<int> IntermediateB()
{
    return InnerAsync();
}

As best I can tell with the debugger, both appear to work exactly the same, but it seems to me that IntermediateB should perform better by avoiding one more await entry in the state machine.

Is that right?

like image 516
MikeZ Avatar asked Dec 03 '17 23:12

MikeZ


People also ask

Does await return a Promise or a value?

Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.

Does async await return a Promise?

The behavior of async / await is similar to combining generators and promises. Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise.

Does await start a new thread?

The async and await keywords don't cause additional threads to be created. Async methods don't require multithreading because an async method doesn't run on its own thread. The method runs on the current synchronization context and uses time on the thread only when the method is active.

What is Awaitable function?

Simply put, an awaitable method or function is one that returns a Task or Task<T> . It doesn't return a data type, instead it returns a process that is asynchronous to the one that is being run at that point in time.


1 Answers

There is subtle differences in this two approaches. If you await failed task the exception will thrown in that method, but if you pass the task thought that method and then await it, the exception will be thrown in the consumer method. Another difference is more rare, in case of consumer awaiting the task and if it occurred with delay, the task can be finished at the await point and bypass the state machine.

like image 147
Hamlet Hakobyan Avatar answered Oct 26 '22 11:10

Hamlet Hakobyan