[英]CA1001 implement IDisposable on async method
Consider following code: 考虑以下代码:
public class Test
{
public async Task Do()
{
await Task.Delay(200);
using (var disposable = new Disposable())
{
disposable.Do();
}
}
}
public class Disposable : IDisposable
{
public void Do()
{
}
public void Dispose()
{
}
}
When I run a code analysis in Visual studio I get a warning: 当我在Visual Studio中运行代码分析时,我收到一个警告:
Warning CA1001 Implement IDisposable on Test.< Do>d__0 because it creates members of the following IDisposable types: 'Disposable'.
警告CA1001在测试时实现IDisposable。<Do> d__0因为它创建了以下IDisposable类型的成员:'Disposable'。
Why do I get this message? 为什么我收到此消息? Disposable class is disposed correctly and I don't store it anywhere.
一次性类正确处理,我不存储在任何地方。
Furthermore this seems to be OK for analyzer: 此外,这似乎适用于分析仪:
public class Test
{
public void Do()
{
using (var disposable = new Disposable())
{
disposable.Do();
}
}
}
That's because compiler generates state machine from your async method, and that state machine class (named <Do>d__0
in this case) contains field of type Disposable
but does not itself implements IDisposable
interface. 这是因为编译器从您的异步方法生成状态机,并且该状态机类(在本例中名为
<Do>d__0
)包含Disposable
类型的字段,但本身并不实现IDisposable
接口。 It doesn't make much sense for analyzer to analyze compiler generated code (and this <Do>d__0
class is marked with CompilerGenerated
attribute). 分析器分析编译器生成的代码没有多大意义(这个
<Do>d__0
类标记有CompilerGenerated
属性)。 Fortunately, there is a setting for code analyzer to avoid compiler generated code: go to project properties, "Code Analysis" tab and check "Suppress results from generated code", and this warning will go away. 幸运的是,代码分析器有一个设置可以避免编译器生成的代码:转到项目属性,“代码分析”选项卡并选中“从生成的代码中抑制结果”,此警告将消失。
If you look at the IL, you'll find that a class <Do>d__0
is created to handle the async stuff: 如果你看一下IL,你会发现创建了一个类
<Do>d__0
来处理异步的东西:
// Nested Types
.class nested private auto ansi sealed beforefieldinit '<Do>d__0'
extends [mscorlib]System.Object
implements [mscorlib]System.Runtime.CompilerServices.IAsyncStateMachine
{
Later on, this class creates an instance of Disposable: 稍后,此类创建一个Disposable实例:
IL_0074: newobj instance void ConsoleApp1.Disposable::.ctor()
That's the class that triggers CA1001 because CA1001 checks the IL, and the generated class does not implement IDisposable
. 这是触发CA1001的类,因为CA1001检查IL,并且生成的类不实现
IDisposable
。 You can safely disregard the CA1001 warning on this particular class. 您可以放心地忽略此特定类的CA1001警告。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.