使用 discard 关键字丢弃任务会导致任何副作用吗?

Does discarding a task with the discard keyword cause any side-effects?

从 C# 7 开始,我们可以使用丢弃 _ 来丢弃未使用的变量。我使用它的其中一件事是在即发即弃的任务中。

考虑这个方法:

public Task Example()
{
    // Do some fire-and-forget stuff.
}

您可以通过简单地不等待任务来触发并忘记此任务:Example(),但是这仍然会给您一个警告。有了 discard 关键字,我们现在可以使用:_ = Example(),它摆脱了这个警告。我想知道这是否有任何我应该注意的令人讨厌的副作用? (除了 MSDN 声明的内容:"This has the effect of suppressing the exception that the operation throws as it is about to complete.")

丢弃语法只是一个语法糖,用来抑制"the return value of this expression is unused"的警告。这两行编译为相同的 IL:

_ = Example();
Example();

它们都成为相同的 call 指令。

因此,如果 Example() 适合您,那么 _ = Example() 也适合您。