C#异步和等待不起作用

jay*_*kum 3 c# asynchronous

为什么以下asyncawait不起作用?我试图了解这是想了解我的代码有什么问题.

class Program
{
    static void Main(string[] args)
    {

        callCount();

    }

    static void count()
    {
        for (int i = 0; i < 5; i++)
        {
            System.Threading.Thread.Sleep(2000);
            Console.WriteLine("count loop: " + i);
        }
    }

    static async void callCount()
    {
        Task task = new Task(count);
        task.Start();
        for (int i = 0; i < 3; i++)
        {
            System.Threading.Thread.Sleep(4000);
            Console.WriteLine("Writing from callCount loop: " + i);
        }
        Console.WriteLine("just before await");
        await task;
        Console.WriteLine("callCount completed");
    }
}
Run Code Online (Sandbox Code Playgroud)

程序将启动count()方法,但在没有完成的情况下退出.随着等待任务; 语句我希望它在退出之前等待完成count()方法的所有循环(0,1,2,3,4).我只得到"计数循环:0".但是它经历了所有的callCount().它就像等待任务一样没有做任何事情.我希望count()和callCount()都异步运行并在完成时返回main.

Art*_*aca 14

当您执行一个async方法时,它会同步开始运行,直到它到达一个await语句,然后其余的代码异步执行,并且执行返回给调用者.

在您的代码callCount()开始同步运行await task,然后返回到Main()方法,并且由于您没有等待方法完成,程序结束而没有方法count()可以完成.

您可以通过更改返回类型看所需的行为Task,并呼吁Wait()Main()方法.

static void Main(string[] args)
{
    callCount().Wait();
}

static void count()
{
    for (int i = 0; i < 5; i++)
    {
        System.Threading.Thread.Sleep(2000);
        Console.WriteLine("count loop: " + i);
    }
}

static async Task callCount()
{
    Task task = new Task(count);
    task.Start();
    for (int i = 0; i < 3; i++)
    {
        System.Threading.Thread.Sleep(1000);
        Console.WriteLine("Writing from callCount loop: " + i);
    }
    Console.WriteLine("just before await");
    await task;
    Console.WriteLine("callCount completed");
}
Run Code Online (Sandbox Code Playgroud)

编辑: 这是你的代码执行方式:

(为了更好地理解,让更改CallCount()返回类型Task)

  1. 程序以Main()方法开头.
  2. CallCount() 方法被调用.
  3. 任务创建,所有这些都在同一个线程中.
  4. 然后任务开始.此时Count(),并行创建一个运行方法的新线程.
  5. 在CallCount()中继续执行,执行循环并打印"就在等待之前".
  6. 然后await task;到达.这是async-await模式发挥作用的时候.await不一样Wait(),它在任务完成之前不阻塞当前线程,但是将执行控制返回给Main()方法,并且在任务完成后将执行所有剩余指令CallCount()(在这种情况下Console.WriteLine("callCount completed");).
  7. Main(),调用CallCount()返回a Task(使用剩余的指令CallCount()和原始任务)并继续执行.
  8. 如果您不等待此任务完成,则执行Main()将继续完成程序和正在销毁的任务.
  9. 如果调用Wait()(如果CallCount()是无效的,你不要有一个任务等待)你让任务完成,持有Main()Count()执行和"callCount完成"正在打印.

如果你想在CallCount()没有返回Main()方法的情况下等待计数任务完成,请调用task.Wait();,所有程序都会等待Count(),但这不是await会做什么的.

链接详细说明了async-await模式.

希望您的代码工作流程图能够帮助您.

在此输入图像描述