繁体   English   中英

CA2000:处理对象警告

[英]CA2000: Dispose object warning

我有以下方法:

    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 ServiceAuditor()'并未沿所有异常路径放置。 在对对象“ new ServiceAuditor()”的所有引用超出范围之前,请调用System.IDisposable.Dispose。

奇怪的是,即使我正在处理对象,我也看不出它为什么抱怨。 您能指出问题出在哪里吗?

您遇到的问题是此行:

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;
}

感谢@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语句的构造函数中完成可抛弃对象的初始化成员。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM