如何编写简单的异步方法? [英] How to write simple async method?
本文介绍了如何编写简单的异步方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用最新CTP5与异步/等待关键字,我写了一些code,这显然不能编译:
Using latest CTP5 with async/await keywords, I wrote some code, which apparently cannot compile:
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();
}
}
是什么的第理由的等待操作者只能在一个方法中使用或λ标有'异步'修饰错误? (我选择的Visual Studio指向的线我)
What is th reason of "The 'await' operator can only be used in a method or lambda marked with the 'async' modifier error?" (I've selected the line which Visual Studio point me to)
推荐答案
我不知道,如果你可以标记为主营异步,但你需要包括异步
关键字在使用任何方法的await
的声明。例如:
I don't know if you can mark Main as async, but you need to include the async
keyword in the declaration of any method that uses await
. For example:
public async void DoStuffAsync ()
{
var myClass = new MyClass ();
int result = await myClass.TestAsync ();
}
这篇关于如何编写简单的异步方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文