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
Why do you ask a question you can answer in a minute by simply testing it?
class Program
{
static void Main(string[] args)
{
MainAsync().Wait();
Console.ReadLine();
}
static async Task MainAsync()
{
await Method1();
}
static async Task Method1()
{
await Method2();
}
static async Task Method2()
{
await Method3();
}
static async Task Method3()
{
Console.Write("Start");
await Task.Delay(1000);
Console.Write("End");
}
}
This creates four different state machines in IL.
The IL code has to be this way, since you can call the methods from anywhere and they have to behave consistently, so any optimization would have to be done on the JIT level, not the C# compiler. If you don't need await
, don't use it - that's your responsibility.
A great example would be method overloads:
static Task Method()
{
return Method("Default");
}
static async Task Method(string someString)
{
await SomeThingAsync(someString);
}
It's still just as asynchronous as if you did another await in the parameter-less method - but it avoids a useless state machine.
The only purpose of the async
keyword is to allow you to use the await
keyword inside a given method. You can still await
a method that isn't async
- the requirement is returning Task
, not having the async
keyword.
Using the same example as before, the await
s are superfluous. A simpler way would be this:
class Program
{
static void Main(string[] args)
{
MainAsync().Wait();
Console.ReadLine();
}
static async Task MainAsync()
{
await Method1();
await Method2();
}
static Task Method1()
{
return Method2();
}
static Task Method2()
{
return Method3();
}
static async Task Method3()
{
Console.Write("Start");
await Task.Delay(1000);
Console.Write("End");
}
}
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.