简体   繁体   English

如何等待条件异步任务

[英]How to await conditional asych task

I have an asynchronous task that is conditional.我有一个有条件的异步任务。 I want to await it if it's called, but, obviously, not wait for it if it's not.如果它被调用,我想等待它,但显然,如果它不是,就不要等待它。

This is what I tried.这是我尝试过的。

Task l;

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

//do other stuff here

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

I get Use of unassigned local variable 'l' compiler error.我得到Use of unassigned local variable 'l'编译器错误。

What's the appropriate way to do this?这样做的合适方法是什么?

In your example, you have not assigned to Task l;在您的示例中,您尚未分配给Task l; . .

You need to at least assign it to null.您至少需要将其分配为 null。

Here is a working sample in a console application:这是控制台应用程序中的工作示例:

    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");
    }

Outputs:输出:

Do other stuff做其他事情
After async process异步处理后
Finished完成的

As far as I know C# does not analyze if conditions in if statement are the same.据我所知,C# 不会分析if语句中的条件if相同。 Next code will work cause actually there will not be any branching at all generated by compiler :下一个代码将起作用,因为实际上编译器根本不会生成任何分支:

Task l;
if (1==1) // or  if(true)
{
    l = Task.CompletedTask;
}
//do other stuff here
if (1==1) // or  if(true)
{
    await Task.WhenAll(l); //unassigned variable error
} 

So in you code you need to initialize local variable, cause using an unassigned local has high likelihood of being a bug (also see this section of specification), so you need to initialize it for example to null or Task.CompletedTask from the get-go:因此,在您的代码中,您需要初始化局部变量,因为使用未分配的局部变量很可能是一个错误(另请参阅规范的这一部分),因此您需要将其初始化为例如nullTask.CompletedTask从 get-走:

Task l = null; // or Task l = Task.CompletedTask;

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

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