I am following this blogpost by @StephenHaunts here https://stephenhaunts.com/2014/10/10/simple-async-await-example-for-asynchronous-programming/#comments
What is the purpose of last return statement in the code, inside LongRunningOperation.
private static async Task<string> LongRunningOperation()
for (counter = 0; counter < 50000; counter++)
return "Counter = " + counter;
What is the purpose of last
returnstatement in the code, inside
To return the string "Counter = 50000" and demonstrate that the loop has been completed. This is not very useful, but, obviously, this is a toy example. You could declare your method as
static async Task instead of
static async Task<string> and not return a value.
As I am calling this
Task.Run, it should return whatever this awaited method is returning by default. Then Why it is not doing that.
What makes you think it is not doing that? Does the following snippet not return the expected result?
string s = await Task.Run(() => LongrunningOperation()); // s should now contain "Counter = 50000".
await will return the potentially unfinished task instead of the result.
If I use
Task.Resultproperty then It'll run behave synchronously and block calling thread, which is not recommended.
Exactly, which is why you shouldn't do it.
How I'll get this returned value printed at calling spot?
By doing something with the return value. Either by assigning it to a string (as demonstrated above), or by printing it directly:
Console.WriteLine(await Task.Run(() => LongrunningOperation()));
And why @Stephen have written that statement when there is no need of it?
That, you'll have to ask Stephen. :-)