Not return value optimization in the traditional sense, but I was wondering when you have a situation like this:
private async Task Method1()
{
await Met
No, the C# compiler doesn't optimize it and it should not. These are conceptually two different things, here is a similar question.
IMO, the major difference is in how exceptions are getting propogated into the caller of Method1
and Method2
. I demo'ed this behavoir here.
In the first case (without the state machine), an exception will be immediately thrown on the caller's stack frame. If it is unhanded, the app may crash right away (unless there is another async
method in the chain of calls on the same stack frame).
In the second case (with the state machine), an exception will remain dormant in the Task
object returned to the caller, until it is observed via await task
or task.Wait()
, some time later. It may get observed on a completely different stack frame, or may not get observed at all. I posted some more details about this here.