首页 > 解决方案 > 如何等待条件异步任务

问题描述

我有一个有条件的异步任务。如果它被调用,我想等待它,但是,显然,如果没有,就不要等待它。

这是我尝试过的。

Task l;

if(condition)
{
    l = MyProcessAsync();
}

//do other stuff here

if(condition)
{
    await Task.WhenAll(l); //unassigned variable error
}

我得到Use of unassigned local variable 'l'编译器错误。

这样做的适当方法是什么?

标签: c#async-await

解决方案


在您的示例中,您尚未分配给Task l;.

您至少需要将其分配给 null。

这是控制台应用程序中的一个工作示例:

    static async Task Main(string[] args)
    {
        var condition = true;
        Task task = null;

        if (condition)
        {
            task = MyProcessAsync();
        }

        Console.WriteLine("Do other stuff");

        if (task != null)
        {
            await task;
        }

        Console.WriteLine("Finished");
        Console.ReadLine();
    }

    static async Task MyProcessAsync()
    {
        await Task.Delay(2000);
        Console.WriteLine("After async process");
    }

输出:


在异步过程
完成后做其他事情


推荐阅读