I was reading about the async pattern in C# in depth, and I decided to take Jon's advice and decompile the async code to actually see what was going on. And I came across two scenarios that confused me a bit as to why they were different.
Consider these two functions:
public static async Task<string> GetValue(){
int count = 0;
count++;
string g = "asdf";
var r = Task.FromResult<string> ("hello");
return g;
}
And
public static async Task<string> GetValue(){
int count = 0;
count++;
string g = "asdf";
var r = await Task.FromResult<string> ("hello");
return g;
}
Now I'd expect the code to ouput the same IL being that they are both async functions so there needs to be a state machine. But to my surprise the C# compiler does create the statemachine in both cases follows all the same code as one would expect, except in the first code block it doesn't actually save any information in the machine. Where in the second it does store all the variables.
Is there a reason that the compiler decides to not save the variables in the state machine and expose two different code paths based on the await keword?