How do I access this job <String> return value in C #?

I am following this blogpost @StephenHaunts here https://stephenhaunts.com/2014/10/10/simple-async-await-example-for-asynchronous-programming/#comments

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

private static async Task<string> LongRunningOperation()
{
     int counter;    
     for (counter = 0; counter < 50000; counter++)
     {
         Console.WriteLine(counter);
     }    
     return "Counter = " + counter;
}

      

Now I know:

  • As I call it LongrunningOperation

    internally Task.Run

    , it should return what this expected method returns by default. Then why isn't it.

  • If I use the property Task.Result

    , then it will run synchronously and block the calling thread, which is not recommended.

I want to ask:

  • How do I get this return value printed when called?

  • And why did @Stephen write this expression when not needed?

Thanks in advance.

+3


source to share


2 answers


What is the purpose of the last statement return

in the code, inside LongRunningOperation

.

To return the string "Counter = 50000" and demonstrate that the loop is complete. It's not very useful, but obviously this is an example of a toy. You can declare your method as static async Task

instead static async Task<string>

and not return a value.

As I call this one LongRunningOperation

internally Task.Run

, it should return all the default expected methods returned. Then why isn't it.

Why do you think this is not the case? 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 a potentially unfinished task instead of a result.

If I use the property Task.Result

, then it will run synchronously and block the calling thread, which is not recommended.



This is why you shouldn't do this.

How do I get this return value printed when called?

Doing something with the return value. Either by assigning it to a string (as shown above), or by printing it directly:

Console.WriteLine(await Task.Run(() => LongrunningOperation()));

      

And why did @Stephen write this expression when not needed?

This, you have to ask Steven. :-)

+4


source


Simplex

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 use async.

-1


source







All Articles