17

使用带有 async/await 关键字的最新 CTP5,我编写了一些代码,显然无法编译:

 class Program
    {
        public class MyClass
        {
            async public Task<int> Test()
            {
                var result = await TaskEx.Run(() =>
                    {
                        Thread.Sleep(3000);
                        return 3;
                    });
                return result;
            }
        }

        static void Main(string[] args)
        {
            var myClass = new MyClass();

            //The 'await' operator can only be used in a method or lambda marked with the 'async' modifier error ??!!
            int result = await myClass.Test();

            Console.ReadLine();
        }
    }

“'await' 运算符只能在标有 'async' 修饰符错误的方法或 lambda 中使用?”的原因是什么?(我选择了 Visual Studio 指向我的行)

4

3 回答 3

8

我不知道您是否可以将 Main 标记为异步,但您需要async在任何使用await. 例如:

public async void DoStuffAsync ()
{
    var myClass = new MyClass ();

    int result = await myClass.TestAsync ();
}
于 2011-07-21T07:50:25.843 回答
4

await不一样Wait(); 执行 anawait是对该方法的重大重写,尤其会影响对该方法如何退出调用者的期望。你是对的,它实际上并没有太多(警告:返回类型),除了告诉编译器启用一些东西(就像开关一样unsafe,如果你考虑一下) - 但请考虑:这实际上在你的例子中非常重要. 如果退出(并且我们假设没有其他线程) - 你的 exe是 toast。走了。不复存在。添加使您认为仅仅因为方法退出并不意味着它已经完成。你真的不想checkeduncheckedMain()asyncMain()在你准备好之前退出。

作为次要效果,此开关还形式化了该方法只能返回诸如Task;之类的东西。如果没有这个开关,你可能会想在以后让它异步,这可能是一个重大的改变。

于 2011-07-21T07:52:12.223 回答
4

异步方法的返回类型可以是 void 或 Task。如果返回类型不是 void,调用者仍然可以在 Main 入口方法中使用 .Net 4 中引入的标准等待机制(不能标记为异步)。这是一个简单的例子:

    static void Main(string[] args)
    {
        string address = "http://api.worldbank.org/countries?format=json";
        Task t = LoadJsonAsync(address);
        // do other work while loading
        t.Wait();

        Console.WriteLine("Hit ENTER to exit...");
        Console.ReadLine();
    }

    private async static Task LoadJsonAsync(string address)
    {
        HttpClient client = new HttpClient();

        HttpResponseMessage response = await client.GetAsync(address);

        // Check that response was successful or throw exception
        response.EnsureSuccessStatusCode();

        // Read response asynchronously as JsonValue and write out top facts for each country
        JsonArray readTask = await response.Content.ReadAsAsync<JsonArray>();
        Console.WriteLine("First 50 countries listed by The World Bank...");
        foreach (var country in readTask[1])
        {
            Console.WriteLine("   {0}, Capital: {1}",
                country.Value["name"],
                country.Value["capitalCity"]);
        }

    }
于 2012-05-10T15:52:26.543 回答