无法理解异步等待行为?

Pra*_*ari 0 c# multithreading asynchronous task-parallel-library async-await

我有以下代码,

using System;
using System.Threading.Tasks;


namespace asyncawait
{
    class Practice
    {
       async Task<int>  Method()
        {
            for (int i = 0; i < int.MaxValue ; i++);

            return 10;
        }

       public async void caller()
        {

           int a = await Method();
           Console.WriteLine("Please print it first");
           Console.WriteLine(a);
           Console.WriteLine("Please print it last");

        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Practice p = new Practice();
            p.caller();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

建设项目时的警告:

Program.cs(9,25,9,31):警告CS1998:这个异步方法缺少'await'运算符并将同步运行.考虑使用'await'运算符等待非阻塞API调用,或'await Task.Run(...)'在后台线程上执行CPU绑定工作.

我的期望是,

预期输出:(第一行应立即打印)

请先打印//不要等,因为我没有使用a,功能等待
10
请最后打印

实际产量:

请先打印//等待执行功能然后打印输出
10
请最后打印

我不明白,为什么我的函数taking time不能异步工作?在看了很多例子后,我真的无法理解概念.

Sco*_*ain 7

所有async关键字都允许您await在函数内使用关键字.如果不调用await该函数的行为与完全不执行任何async关键字的行为相同.

从msdn页面" 使用异步和等待的异步编程(C#和Visual Basic)" 查看此图像

在此输入图像描述

如果你按照黑线所有在同一个线程上发生的事情,直到你到达为止6.然后,此时函数返回并在结果准备好后继续.因为await代码中没有代码,所以"黑线"会贯穿整个函数.

为了使它像你想要的那样工作,你需要在函数中发出信号,它应该回到调用者.

   async Task<int>  Method()
    {
        for (int i = 0; i < int.MaxValue ; i++)
        {
            await Task.Yield(); //Your function now returns to the caller at this point then comes back later to finish it. (Your program will be much slower now because it is going to wait int.MaxValue times.)
        }
        return 10;
    }
Run Code Online (Sandbox Code Playgroud)