I am trying to understand how Async and Await works. How control travel in the program. Here is the code which I was trying to understand.
public async Task MyMethod()
{
Task<int> longRunningTask = LongRunningOperation();
//indeed you can do independent to the int result work here
MySynchronousMethod();
//and now we call await on the task
int result = await longRunningTask;
//use the result
Console.WriteLine(result);
}
public async Task<int> LongRunningOperation() // assume we return an int from this long running operation
{
await Task.Delay(5000); //5 seconds delay
return 1;
}
private void Button_Click_3(object sender, RoutedEventArgs e)
{
MyMethod();
}
When button click occur then MyMethod()
will be called and from the MyMethod LongRunningOperation()
will be called and it take 5 sec to complete. so my question is
What is the meaning of this line
Task longRunningTask = LongRunningOperation();
what this does int result = await longRunningTask;
The above line could be committed and one line we can construct like
Task<int> longRunningTask = await LongRunningOperation();
or
int result = await longRunningTask;
Please can someone explain to me the above code which is not clear to me.
1) if the longRunningOperation hasn't finished and is still running, MyMethod() will return to its calling method, thus the main thread doesn't get blocked. When the longRunningOperation is done then a thread from the ThreadPool (can be any thread) will return to MyMethod() at its previous state and continue execution (in this case printing the result to the console).
A second case would be that the longRunningOperation has already finished its execution and the result is available. When reaching the await longRunningOperation the compiler knows that it has the result and will keep on executing code on the very same thread. (in this case printing result to console).
point 1 is not at all clear to me like the statement "if the longRunningOperation hasn't finished and is still running, MyMethod() will return to its calling method
"
if possible explain the point one in more detail. thanks
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…