Eqra Eqra -4 years ago 122
C# Question

How I'll access this Task <String> return value in C#?

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:


  1. 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.

  2. 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:


  1. How I'll get this returned value printed at calling spot?

  2. And why @Stephen have written that statement when there is no need of it?



Thanks in advance.

Answer Source

What is the purpose of last return statement in the code, inside LongRunningOperation.

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 inside 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".

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. :-)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download