首页 > 解决方案 > 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?

标签: c#async-awaitnull-coalescing-operator

解决方案


我相信这是一个优先问题。您的代码实际上是:

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;

推荐阅读