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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With