【问题标题】:Async/await: Making method async异步/等待:使方法异步
【发布时间】:2013-09-13 19:18:21
【问题描述】:

我正在尝试做一个简单的示例,但我什至没有掌握基础知识。这段代码有什么问题?想象一下Calculate() 需要几秒钟。

    static void Main(string[] args)
    {
        int result = await Calculate();

        Console.WriteLine(result);
        Console.ReadLine();
    }

    static async Task<int> Calculate()
    {
        return 1;
    }

【问题讨论】:

  • 使用“经典”方法从 main 中的任务中获取结果;)
  • 您可能会发现我的async intro 很有帮助。

标签: c# asynchronous task async-await


【解决方案1】:

只需将您的主要更改为:

static void Main(string[] args)
{
    int result = Calculate().Result;

    Console.WriteLine(result);
    Console.ReadLine();
}

一旦您使用了await 关键字,必须将周围的方法标记为async,正如其他人提到的那样,Main 是不可能的。 由于async 方法如Calculate 仍然返回良好的旧Task 对象,请随意使用处理它们的“旧”方式:使用Result 等待结果。当然这是一个阻塞操作——但没有理由在Main 内部不阻塞,对吧? ;)

【讨论】:

    【解决方案2】:

    你可以这样做:

    static void Main()
    {
        WrapMain();
    }
    
    static async void WrapMain()
    {
        int result = await Calculate();
    
        Console.WriteLine(result);
        Console.ReadLine();
    }
    
    static async Task<int> Calculate()
    {
        return await Task.Run(() =>
        {
            return 1;
        });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多