结果实现 IDisposable 时丢弃异步结果
Discard async result when result implements IDisposable
using var notNeeded = await foo();
foo
returns 实现 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
有没有更优雅的方式?
我会说立即处理它
var notNeeded = await foo();
notNedded.Dispose();
我倾向于立即处理 non-needed IDisposable
对象:
(await foo()).Dispose();
...如果是 IAsyncDisposable
:
await (await foo()).DisposeAsync();
using var notNeeded = await foo();
foo
returns 实现 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
有没有更优雅的方式?
我会说立即处理它
var notNeeded = await foo();
notNedded.Dispose();
我倾向于立即处理 non-needed IDisposable
对象:
(await foo()).Dispose();
...如果是 IAsyncDisposable
:
await (await foo()).DisposeAsync();