繁体   English   中英

为什么在等待它被认为是异步的同一行上调用一个方法?

[英]Why is invoking a method on the same line as awaiting it considered asynchronous?

我正在查看http://www.dotnetperls.com/async上的示例以更好地理解async / await,但以下内容让我感到困惑:

我理解为什么下面的例子被认为是异步的。 调用HandleFileAsync ,调用Console.WriteLine ,然后在继续之前等待任务完成。

static async void ProcessDataAsync()
{
     // Start the HandleFile method.
     Task<int> task = HandleFileAsync("C:\\enable1.txt");

     // Control returns here before HandleFileAsync returns.
     // ... Prompt the user.
     Console.WriteLine("Please wait patiently " +
         "while I do something important.");

     // Wait for the HandleFile task to complete.
     // ... Display its results.
     int x = await task;
     Console.WriteLine("Count: " + x);
}

但是在下面的示例中,我们等待Task.Run的调用,该调用运行一个动作:

static async void Example()
{
     // This method runs asynchronously.
     int t = await Task.Run(() => Allocate());
     Console.WriteLine("Compute: " + t);
}

那么,如果我们在等待 Task.Run的完成,那么异步发生了什么呢? 我们认为一旦我们等待后续任务的执行完成就会成为阻塞调用,在这种情况下,在同一行上调用它。

我错过了什么?

我们认为一旦我们等待后续任务的执行完成就会成为阻塞调用,在这种情况下,在同一行上调用它。 我错过了什么?

你的信念是错误的; 这就是你所缺少的。 “等待”的意思是“现在返回,在我们异步等待时运行别的东西,当结果可用时,回到这里。”

获取任务的结果会做您认为等待的事情。 如果它只是同步获取任务的结果,我们就不必发明等待! 异步获取任务的结果。

虽然我们在这,但这个评论是错误的:

// Control returns here before HandleFileAsync returns.

怎么可能呢? HandleFileAsync返回了一个任务! 如果HandleFileAsync没有返回,控制如何通过手头的任务达到这一点? 当然它回来了。

这条评论具有误导性:

// Wait for the HandleFile task to complete.

这应该是异步等待任务完成。 通过异步等待,记住,我们的意思是“现在返回,继续运行更多的工作,当任务完成时,在此时恢复结果。”

如果我是你,我会找到更好的教程。

到底发生了什么异步?
考虑一下:

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static volatile uint i;
        static uint Test()
        {
            Thread.Sleep(1000);
            i = 2; //uint.MaxValue;
            while (i-- > 0) { }
            return i;
        }

        static bool done;
        static async void Example()
        {
            var t = await Task.Run(() => Test());
            Console.WriteLine("result: " + t);
            done = true;
        }
        static void Main(string[] args)
        {
            Example();
            Console.WriteLine("wait: Control returns here before Example() returns ");
            while (!done) { }
            Console.WriteLine("done ");
        }
    }
}

Example(); 本身就是异步发生的。 所以,如果你删除while (!done) { }
程序在Example()完成之前退出。
我希望这有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM