-1

最近我尝试了解新的 C# 特性,异步编程的 async/await 关键字。当我在网上搜索时,我遇到了这个例子:

    static void Main(string[] args)
    {
        Console.WriteLine("Task based APM demo");

        // Call Exponnent() asynchronously.
        // And immediately return the control flow.
        // If I don't put a Task here, the program will sometimes
        // terminate immediately.
        Task t = new Task(async () =>
        {
            int result = await Program.Exponent(10);

            // After the operation is completed, the control flow will go here.
            Console.WriteLine(result);
        });

        t.Start();
        Console.ReadKey();
    }

    static async Task<int> Exponent(int n)
    {
        Console.WriteLine("Task started");
        return await TaskEx.Run<int>(() => 2 << (n - 1));
    }
}

我对此以及这些陈述的行为方式有疑问。首先,据我了解,当我们想要释放该进程并返回调用者上下文时使用的等待表达式。但是为什么这个表达式在 Exponent 方法调用它的那一行使用 this 呢?事实上,当编译器面对这行程序时会发生什么?字母问题是,为什么程序使用“TaskEx.Run”在 Exponent 方法的主体中返回结果?是否可以使用“return await (() => 2 << (n - 1));” 只要?编译器如何处理这一行?

提前致谢

4

1 回答 1

1

但是为什么这个表达式在指数调用它的那一行使用这个呢?

我不确定你这个问题是什么意思。 await Task.Run<int>(() => 2 << (n - 1));告诉编译器暂停当前方法的执行,直到任务完成。在任务方面,这类似于:

Task.Run<int>(() => 2 << (n - 1)).ContinueWith(t=>return t.Result);

但是,当然,你不能return继续。该async关键字不仅告诉编译器await该方法中可能有一个或多个运算符,而且还设置了一个状态机来管理从异步操作开始和返回的不同状态转换。同样,这可能会影响与调用者异步相关的方法执行方式。

As to the Task used in Main: you can't await a method call in Main, so, I assume the Task is used to still use the await operator. But, it seems redundant. I would probably simply have another method to use await:

    static async void Method()
    {
        Console.WriteLine(await Exponent(10));
    }

Then re-write Main:

    static void Main(string[] args)
    {
        Method();
        Console.ReadLine();
    }

But, I don't know the reasons behind why the code was originally written that way or even if there was a real purpose.

Is it possible to use "return await (() => 2 << (n - 1));"

It is not possible to write this line of code because nothing asynchronous is being performed. () => 2 << (n - 1) neither returns a Task object not has an GetAwaiter method associated with it; so, it can be executed asynchronously. thus, it can't be "awaited".

于 2012-09-22T13:25:28.603 回答