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

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

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

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’

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

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

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

看看这里: async(C#参考) 。

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

你需要在你的方法中放入异步,我修改了你的代码,因为Click事件签名没有返回int,你的方法是AccessTheWebAsync ,所以我把它移动到另一个方法async返回int,无论如何我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 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); } }