gpt4 book ai didi

c# - 当结果实现 IDisposable 时丢弃异步结果

转载 作者:行者123 更新时间:2023-12-02 01:35:38 26 4
gpt4 key购买 nike

using var notNeeded = await foo();

foo 返回一个实现 IDisposable 的对象,但该对象可以立即丢弃。写这行代码的方式是什么?

using var notNeeded = await foo(); // (1) possible lint error: unused variable
using var _ = await foo(); // (2) looks clean but lives until the end of the function (which is rarely an issue)
using _ = await foo(); // (3) not legal
using (await foo()); // (4) possible lint error: possible mistaken empty statement
using (await foo()) {} // (5) looks like a mistake but actually does call Dispose() immediately

还有更优雅的方式吗?

最佳答案

我倾向于立即处置不需要的 IDisposable 对象:

(await foo()).Dispose();

...如果它是 IAsyncDisposable:

await (await foo()).DisposeAsync();

关于c# - 当结果实现 IDisposable 时丢弃异步结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72446598/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com