如何在 C# 中的三元运算符中使用await?

rin*_*mau 3 c# conditional-operator async-await

SoftUpdateAsync使用此代码,对and的调用UpdateAsync似乎没有等待,我收到了死锁事务的错误。

_ = await _tabRepository.IsReferencedFromAnotherTableAsync(entity.Id)
    ? _tabRepository.SoftUpdateAsync(entity)
    : _tabRepository.UpdateAsync(entity);
Run Code Online (Sandbox Code Playgroud)

该函数IsReferencedFromAnotherTableAsync返回一个布尔值,UpdateAsync并且SoftUpdateAsync返回一个任务。

但是,如果我将代码写为

if (await _tabRepository.IsReferencedFromAnotherTableAsync(entity.Id))
    await _tabRepository.SoftUpdateAsync(entity);
else
    await _tabRepository.UpdateAsync(entity);
Run Code Online (Sandbox Code Playgroud)

一切似乎都正常工作。

我可以使用三元运算符代替 if then else 吗?

我尝试过:

_ = await _countdownRepository.IsReferencedFromAnotherTableAsync(entity.Id)
    ? await _countdownRepository.SoftUpdateAsync(entity)
    : await _countdownRepository.UpdateAsync(entity);
Run Code Online (Sandbox Code Playgroud)

和

await _countdownRepository.IsReferencedFromAnotherTableAsync(entity.Id)
    ? await _countdownRepository.SoftUpdateAsync(entity)
    : await _countdownRepository.UpdateAsync(entity);
Run Code Online (Sandbox Code Playgroud)

两者都会导致错误:

第一个是“不能对 void 类型的值进行赋值”,第二个是“只有赋值、调用、递增、递减和新对象表达式可以用作语句”

Jon*_*eet 12

我强烈怀疑你想要:

await (await _countdownRepository.IsReferencedFromAnotherTableAsync(entity.Id)
    ? _countdownRepository.SoftUpdateAsync(entity)
    : _countdownRepository.UpdateAsync(entity));
Run Code Online (Sandbox Code Playgroud)

或者为了更清楚地说明发生了什么:

var task = await _tabRepository.IsReferencedFromAnotherTableAsync(entity.Id)
    ? _tabRepository.SoftUpdateAsync(entity)
    : _tabRepository.UpdateAsync(entity);
await task;
Run Code Online (Sandbox Code Playgroud)

我强烈怀疑问题是_tabRepository.SoftUpdateAsync(entity)(和另一个分支)都返回Task- 当您等待它时,不会返回任何内容。您不能使用条件 ?: 表达式,其中两个分支不返回任何内容。因此,您需要确定要等待哪个任务,然后等待它 - 这就是我上面的两个选项的作用。

  • @rinomau:您调用的方法的签名*是*重要的。这是我在您的情况下发布的示例:https://gist.github.com/jskeet/cb8d280ae9be1d627ab19e8a10d31488 (2认同)