Dan*_*elV 0 c# warnings dispose fxcop
我有以下方法:
public byte[] HtmlToDoc(string hmtl, string userId)
{
byte[] data;
var auditor = new ServiceAuditor
{
User = userId
};
try
{
using (var tx = new ServerText())
{
tx.Create();
tx.Load(Server.HtmlDecode(hmtl), StringStreamType.HTMLFormat);
tx.Save(out data, BinaryStreamType.MSWord);
}
}
catch (Exception e)
{
auditor.Errormessage = e.Message + "/n " + e.StackTrace;
data = new byte[0];
}
finally
{
auditor.Save();
auditor.Dispose();
}
return data;
}
Run Code Online (Sandbox Code Playgroud)
我在编译期间收到以下警告:
警告 CA2000:Microsoft.Reliability:在方法“DocCreator.HtmlToDoc(string, string)”中,对象“new ServiceAuditor()”未沿所有异常路径处理。在对象“new ServiceAuditor()”上调用 System.IDisposable.Dispose 在对它的所有引用都超出范围之前。
奇怪的是,即使我正在处理该对象,我也不明白为什么它会抱怨。你能指出问题出在哪里吗?
您遇到的问题是这一行:
auditor.Save();
Run Code Online (Sandbox Code Playgroud)
如果抛出异常,则下一行将不会运行,它负责处理您的auditor对象。因此,您可以将Save调用包装在另一个try/ 中catch,但实际上您应该只依赖该using语句为您执行此操作,因为它隐式调用了该Dispose方法,例如:
public byte[] HtmlToDoc(string hmtl, string userId)
{
byte[] data;
//Add using statement here and wrap it around the rest of the code
using(var auditor = new ServiceAuditor { User = userId })
{
try
{
using (var tx = new ServerText())
{
tx.Create();
tx.Load(Server.HtmlDecode(hmtl), StringStreamType.HTMLFormat);
tx.Save(out data, BinaryStreamType.MSWord);
}
}
catch (Exception e)
{
auditor.Errormessage = e.Message + "/n " + e.StackTrace;
data = new byte[0];
}
finally
{
auditor.Save();
//No need to manually dispose here any more
}
}
return data;
}
Run Code Online (Sandbox Code Playgroud)