c# - 如何等待条件异步任务
问题描述
我有一个有条件的异步任务。如果它被调用,我想等待它,但是,显然,如果没有,就不要等待它。
这是我尝试过的。
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'
编译器错误。
这样做的适当方法是什么?
解决方案
在您的示例中,您尚未分配给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");
}
输出:
在异步过程
完成后做其他事情
推荐阅读
- angular - 如何访问 Swiper Angular 组件的虚拟幻灯片方法
- html - 选择标签上的默认值的ReactJS问题
- sql - 更新oracle之前触发问题[PL/SQL]
- linux-kernel - 中断嵌套,排序
- javascript - 生产中的外部 API 问题 - React.js
- .net - 是否可以增加 HttpClient 中的最大 URI 长度?(无效的 URI:uri 字符串太长)
- javascript - Promise 链接错误不会正确传递给 catch
- python - 删除或修改连续的重复行
- swift - 如何快速禁用 UI 键盘键
- c# - EF Core 3.1 流畅的 API