首页 > 解决方案 > C#异步递归函数不能正常工作?

问题描述

这是我的代码:

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

    static async void update()
    {
        await Task.Delay(100);
        Console.WriteLine("X");
        update();
    }
}

控制台从不输出任何文本,我也不知道为什么。我究竟做错了什么?

标签: c#asynchronousrecursion

解决方案


你的Main方法不是async,所以它不会等待你的update方法。此外,您的update方法应该返回 aTask以便您的Main方法可以等待它。

static async Task Main(string[] args)
{
    await update();
}

static async Task update()
{
    await Task.Delay(100);
    Console.WriteLine("X");
    await update();
}

推荐阅读