Reputation: 763
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()
{
int counter;
for (counter = 0; counter < 50000; counter++)
{
Console.WriteLine(counter);
}
return "Counter = " + counter;
}
Now what I know is:
As I am calling this LongrunningOperation
inside Task.Run
, it should return whatever this awaited method is returning by default. Then Why it is not doing that.
If I use Task.Result
property then It'll run behave synchronously and block calling thread, which is not recommended.
What I want to ask is:
How I'll get this returned value printed at calling spot?
And why @Stephen have written that statement when there is no need of it?
Thanks in advance.
Upvotes: 3
Views: 1842
Reputation: 1284
A symple
private async Task DoSomething()
{
var counter = await LongRunningOperation();
//More code.
}
Will do.
EDIT:
You can also do:
private void DoSomething()
{
var counter = LongRunningOperation().GetAwaiter().GetResult();
//More code
}
If you don't want to make the method async.
Upvotes: -1
Reputation: 172270
What is the purpose of last
return
statement in the code, insideLongRunningOperation
.
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
LongrunningOperation
insideTask.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".
Note: Calling Task.Run
without await
will return the potentially unfinished task instead of the result.
If I use
Task.Result
property 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. :-)
Upvotes: 5