How do I get the return value of an async method?
Hello I am trying to understand the concept of tasks and asynchronous methods. I've been playing around with this code for a while, to no avail. Can someone please tell me how I can 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;
}
}
}
source to share
To get the value from Task
, you can await
execute a task that asynchronously waits for the task to complete and then returns the result. Another option is to invoke Task.Result
, which blocks the current thread until the result is available. This can cause a dead end in graphical applications, but in console applications this is fine because they don't SynchronizationContext
.
You cannot use await
in a method Main
as it cannot be async
, so one of the options 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();
}
Another option is to create a method async
that you call from Main
and await
tasks within it. You will still have to block async
while waiting for the method to complete so that you can call the Wait()
method as a result.
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();
}
source to share