小编rin*_*mau的帖子

如何在 C# 中的三元运算符中使用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 类型的值进行赋值”,第二个是“只有赋值、调用、递增、递减和新对象表达式可以用作语句”

c# conditional-operator async-await

3
推荐指数
1
解决办法
356
查看次数

标签 统计

async-await ×1

c# ×1

conditional-operator ×1