c# - 如何使用 await 简单安全地调用可为空的委托(delegate)

标签 c# async-await task-parallel-library nullreferenceexception func

我有 func<Task>我的项目中的代表可以为空。有没有办法让这样的代表的调用更简单,如下所示?

public async Task Test()
{
    Func<Task> funcWithTask = null;

    await (funcWithTask != null ? funcWithTask.Invoke() : Task.CompletedTask);
}

最佳答案

Is there any way to make the call of such a delegate simpler as displayed below?


有替代方案:
if (funcWithTask != null) await funcWithTask();
或者:
await (funcWithTask?.Invoke() ?? Task.CompletedTask);
第二个使用 null-conditional operator ?. , 只调用 Invoke()funcWithTask不为空,null-coalescing operator ??当左侧操作数为空时返回右侧操作数(在这种情况下为 Task.CompletedTask)。

关于c# - 如何使用 await 简单安全地调用可为空的委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67623315/

相关文章:

c# - 如何遍历字典?

c# - 推荐使用 Task.WhenAll 循环执行任务的方法

c# - 在异步函数中,为什么我必须等待?

c# - 在 akka.net 中立即触发多个线程

c# - 异步运行同步方法的正确方法是什么

c# - 在两个日期范围之间相交的天数

c# MailMessage 对象问题

c# - 在没有 Wait() 的情况下使用 TPL 处理异常

C# SFTP上传文件

javascript - Async-Await:即使一个错误,如何在多个等待调用中获取数据?