Eqra Eqra - 1 year ago 61
C# Question

How to get value returned from async Task<string> function(); in C#

I have an async method and I want to get a message from the same method when it gets done.

Below is the code

static async Task<string> pizza()
{
await Task.Delay(10);
for (int i = 0; i < 100; i++)
{
//Console.WriteLine("Processing pizza...");
}
return "Pizza is ready";

}


And I want to get receive this message at calling point

....... code
Task t=null;
switch (option)
{
case 1:
{

await Task.Run(() =>
{

t=pizza();// asynchronous method

});
Console.WriteLine(t.ToString());
}
break;
.... other code

Answer Source

Do you need the Task.Run part? You can await of you are inside an async method:

var result = await pizza();

Console.WriteLine(result);

You can also call result:

var result = pizza().Result;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download