我有以下方法:
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;
}在编译过程中,我收到以下警告:
警告CA2000: Microsoft.Reliability :在方法'DocCreator.HtmlToDoc(string,string)‘中,对象'new ()’不是沿所有异常路径释放的。在所有对对象的引用超出作用域之前,在对象'new ()‘上调用ServiceAuditor。
奇怪的是,我不明白为什么它在抱怨,即使我正在处理这个物体。你能指出问题在哪里吗?
发布于 2018-02-12 11:15:44
问题是这句话:
auditor.Save();如果这引发异常,则下一行将不会运行负责处理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;
}发布于 2018-02-12 15:15:46
谢谢@DavidG对您的响应,在提到的行中肯定有一个错误点,但是引起警告的是对象的初始化:
//Add using statement here and wrap it around the rest of the code
using(var auditor = new ServiceAuditor { User = userId })
{
try
{ ...应:
using(var auditor = new ServiceAuditor())
{
auditor.User = userId;
try
{ ...我在这里找到了这个问题的参考资料,CA2000:处置。
不应在using语句的构造函数中初始化一次性对象的成员。
https://stackoverflow.com/questions/48744738
复制相似问题