如何编写简单的异步方法?

gho*_*ord 17 c# async-ctp

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

 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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

Bod*_*ick 8

我不知道你是否可以将Main标记为异步,但是你需要async在任何使用方法的声明中包含关键字await.例如:

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

    int result = await myClass.TestAsync ();
}
Run Code Online (Sandbox Code Playgroud)

  • 在C#5版本中,如果将Main标记为异步,则会出现错误:"无法使用'async'修饰符标记入口点" (8认同)