Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get the return value of an async method?

Hello I'm trying to understand the concept of task and async methods. I've been playing with this code for a while now to no avail. Could someone please tell me how can I get the return value from the test() method and assign that value to a variable?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
   class Program
   {

    static  void Main(string[] args)
    {

        Task test1 = Task.Factory.StartNew(() => test());
        System.Console.WriteLine(test1);
        Console.ReadLine();
    }

    public static async Task<int> test()
    {
        Task t = Task.Factory.StartNew(() => {   Console.WriteLine("do stuff"); });
        await t;
        return 10;
    }
}
}
like image 380
Patrick Riddick Avatar asked Sep 30 '22 23:09

Patrick Riddick


1 Answers

To get the value out of a Task you can await the task which asynchronously waits for the task to complete and then returns the result. The other option is to call Task.Result which blocks the current thread until the result is available. This can cause a deadlock in GUI apps but is ok in console apps because they don't have a SynchronizationContext.

You can't use await in the Main method as it can't be async so one option is to use test1.Result:

static  void Main(string[] args)
{

    Task<int> test1 = Task.Factory.StartNew<int>(() => test());
    System.Console.WriteLine(test1.Result); // block and wait for the result
    Console.ReadLine();
}

The other option is to create an async method that you call from Main and await the task inside it. You still may need to block waiting for the the async method to finish so you can call Wait() on the result of that method.

static  void Main(string[] args)
{
    MainAsync().Wait(); // wait for method to complete
    Console.ReadLine();
}

static async Task MainAsync()
{
    Task<int> test1 = Task.Factory.StartNew<int>(() => test());
    System.Console.WriteLine(await test1); 
    Console.ReadLine();
}
like image 96
NeddySpaghetti Avatar answered Oct 06 '22 19:10

NeddySpaghetti