我有一个有条件的异步任务。如果它被调用,我想等待它,但显然,如果它不是,就不要等待它。
这是我尝试过的。
Task l;
if(condition)
{
l = MyProcessAsync();
}
//do other stuff here
if(condition)
{
await Task.WhenAll(l); //unassigned variable error
}
Run Code Online (Sandbox Code Playgroud)
我收到Use of unassigned local variable 'l'编译器错误。
这样做的合适方法是什么?
小智 6
在您的示例中,您尚未分配给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");
}
Run Code Online (Sandbox Code Playgroud)
输出:
异步处理
完成后做其他事情