如何获取异步方法的返回值?

Pat*_*ick 5 .net async-await

您好,我正在尝试了解任务和异步方法的概念。我一直在玩这个代码一段时间无济于事。有人能告诉我如何从 test() 方法中获取返回值并将该值分配给变量吗?

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;
    }
}
}
Run Code Online (Sandbox Code Playgroud)

Ned*_*nov 4

要从 a 中获取值,Task您可以await异步等待任务完成,然后返回结果。另一种选择是调用Task.Result它阻塞当前线程,直到结果可用。这可能会在 GUI 应用程序中导致死锁,但在控制台应用程序中没有问题,因为它们没有SynchronizationContext.

您不能await在该Main方法中使用,因为它不能,async所以一种选择是使用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();
}
Run Code Online (Sandbox Code Playgroud)

另一个选项是创建一个async您从中调用的方法Main以及await其中的任务。您可能仍然需要阻止等待该async方法完成,以便您可以调用Wait()该方法的结果。

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();
}
Run Code Online (Sandbox Code Playgroud)

  • 处理“async-await”时,使用“Task.Run”而不是“Task.Factory.StartNew”。 (3认同)