关于异步编程与异步和等待c#的问题

时间:2013-11-14 08:05:56

标签: c# asynchronous async-await

我正在学习如何使用Async和Await c#。所以我得到一个链接http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx#BKMK_WhatHappensUnderstandinganAsyncMethod

从这里我尝试从VS2012 IDE运行代码但是收到错误。 此功能引发错误。

private void button1_Click(object sender, EventArgs e)
        {
            int contentLength = await AccessTheWebAsync();

            label1.Text= String.Format("\r\nLength of the downloaded string: {0}.\r\n", contentLength);
        }

此行给出错误await AccessTheWebAsync(); 'await'运算符只能在异步方法中使用。请考虑使用“async”修饰符标记此方法,并将其返回类型更改为“Task”

我做错了什么。请指导我如何运行代码。感谢

2 个答案:

答案 0 :(得分:5)

它非常清楚地表明您必须使用async修饰您的方法。像这样:

// note the 'async'!
private async void button1_Click(object sender, EventArgs e)

看看这里:async (C# Reference)

  

通过使用async修饰符,可以指定方法,lambda表达式或匿名方法是异步的。如果在方法或表达式上使用此修饰符,则将其称为异步方法。

答案 1 :(得分:1)

你需要在你的方法中放入异步,我修改了你的代码,因为Click事件签名没有返回int,而你的方法AccessTheWebAsync也是如此,所以我将它移动到另一个返回int的async方法,无论如何我async和await是一种语法糖,建议您在使用这些关键字时查看代码的真实情况,请查看此处:http://www.codeproject.com/Articles/535635/Async-Await-and-the-Generated-StateMachine

private async void button1_Click(object sender, EventArgs e)
        {
            await ClickAsync();
        }

        private async Task<int> AccessTheWebAsync()
        {

            return await Task.Run(() =>
                {
                    Task.Delay(10000);  //Some heavy work here
                    return 3; //replace with real result
                });

        }

        public async Task ClickAsync()
        {
            int contentLength = await AccessTheWebAsync();

            label1.Text = String.Format("\r\nLength of the downloaded string: {0}.\r\n", contentLength);
        }
    }
相关问题