Call chain for async / await ... waiting for the expected or returning the expected?

For the asynchronous method:

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

And calling it through an intermediate method, should the intermediate method expect an asynchronous method (IntermediateA) or just return the task (intermediate)?

 pubic async Task<int> IntermediateA() { return await InnerAsync(); } private Task<int> IntermediateB() { return InnerAsync(); } 

As far as I can tell with the debugger, both seem the same, but it seems to me that IntermediateB should work better, avoiding another wait record on the destination machine.

Is it correct?

+5
source share
1 answer

There are subtle differences in these two approaches. If you await did not complete the task, an exception will be thrown in this method, but if you pass the task, think that this method, and then await , the exception will be thrown in the user method. Another difference is less common: if a consumer waits for a task and, if this happens with a delay, the task can be completed at the waiting point and bypass the state machine.

+6
source

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


All Articles