c# - Awaiting with null coalescing operator thrown exception
问题描述
I'm encountering some strange behavior.
When running this piece of code:
var foo = await actionContext.RequestContext?.Principal?.ToUserTokenAsync() ?? UserToken.UnidentifiedUser;
Principal
is null
at runtime and I get a null reference exception.
Why it's not just returning --> UserToken.UnidentifiedUser
?
解决方案
我相信这是一个优先问题。您的代码实际上是:
var foo = (await actionContext.RequestContext?.Principal?.ToUserTokenAsync()) ??
UserToken.UnidentifiedUser;
换句话说,如果等待的结果为空,则返回UserToken.UnidentifiedUser
。但是您仍然尝试进行等待 - 这意味着您可能会等待无效的内容,这会失败。
我怀疑你想要的是:
var task = actionContext.RequestContext?.Principal?.ToUserTokenAsync()
?? Task.FromResult(UserToken.UnidentifiedUser);
var foo = await task;
或者避免在有 null 时完全等待:
var task = actionContext.RequestContext?.Principal?.ToUserTokenAsync();
var foo = task != null ? await task : UserToken.UnidentifiedUser;
推荐阅读
- java - com.sun.tools.javadoc.Main.execute 在 jdk 11 中运行 Doclet 的替代方法是什么?
- r - 如何在 Rstudio 中对变量进行分类、计算变量并定义它们的百分比
- elixir - 将牛仔升级到牛仔 2 时出现错误
- wordpress - 自定义事件跟踪不发送事件
- c# - 为什么在 Asp.Net MVC 中提交表单时会话会过期?
- angular - 如何在 Angular cli 中打开外部链接?
- typescript - 如何检查字符串是否是 TypeScript 中特定接口的属性
- git - 在 GIT 历史记录中搜索文件?
- python - 使用 Tkinter 快速显示图像
- json - 使用 Scala 处理大型 JSON