【问题标题】:Where and how to place await keyword在哪里以及如何放置 await 关键字
【发布时间】:2014-01-06 02:18:06
【问题描述】:

我正在尝试了解异步的工作原理。这是我的代码:

class Program
{
    static void Main(string[] args)
    {
        Task<string> strReturned = returnStringAsync();
        Console.WriteLine("hello!");
        string name = await strReturned; //error: The 'await' operator can only be used 
                                         //within an async method. Consider marking this 
                                         //method with the 'async' modifier and changing 
                                         //its return type to 'Task'

        Console.WriteLine(name);
    }

    static async Task<string> returnStringAsync()
    {
        Thread.Sleep(5000);
        return "Richard"; 
    }
}

有什么问题吗?

【问题讨论】:

  • 那么,你不明白错误告诉你什么?
  • 错误在strReturned旁边。
  • async 方法中,您应该使用await Task.Delay(5000) 而不是Thread.Sleep(5000)
  • @PhillipScottGivens 不,它不会编译
  • @Richard77:您可能会发现我的async/await intro 很有帮助。

标签: c# async-await


【解决方案1】:

这行得通

class Program
{
    static void Main(string[] args)
    {
        Task<string> str = returnStringAsync();
        Console.WriteLine("hello!");

        string name = str.Result;

        Console.WriteLine(name);
    }

    static async Task<string> returnStringAsync()
    {
        await Task.Delay(5000);
        return "Richard"; 
    }
}

【讨论】:

  • 是的,这行得通,但这几乎是唯一一个在async Task 上调用Result(或Wait())是个好主意的情况。在大多数其他情况下,这样做会导致死锁。
  • @svick。然后给出一个更好的方法来编写这段代码。事实上,这是我第一次在 async 和 await 上编写代码。在那个领域,对我来说一切都是新的。
  • 在这种特定情况下(控制台应用程序运行async 代码),使用Result 正确的方法。但在大多数其他情况下,情况并非如此。
猜你喜欢
  • 2011-08-01
  • 1970-01-01
  • 2021-05-15
  • 1970-01-01
  • 1970-01-01
  • 2019-07-23
  • 2011-09-04
  • 2017-10-05
  • 1970-01-01
相关资源
最近更新 更多