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

并且我在编译期间收到以下警告:

warning CA2000: Microsoft.Reliability : In method 'DocCreator.HtmlToDoc(string, string)', object 'new ServiceAuditor()' is not disposed along all exception paths. Call System.IDisposable.Dispose on object 'new ServiceAuditor()' before all references to it are out of scope.

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

您遇到的问题是这一行:

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: Dispose ...

Initializing members of a disposable object should not be done in the constructor of a using statement.