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

12,699

Solution 1

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;

Solution 2

You can either

var pizza = await pizza();

Or

var pizza = pizza().GetAwaiter().GetResult();
Share:
12,699
Iqra.
Author by

Iqra.

I'm a Software Engineer and author (at PACKT, C# Corner, and Code Project). I love to work on my ideas and execute them only after validating the 'return on investment' where investment is equal to my time and effort. Ummm, I love running in the morning and walking at night. Also, I love fruits and anyyy kind of dessert.

Updated on June 04, 2022

Comments

  • Iqra.
    Iqra. almost 2 years

    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