【问题标题】:what is wrong with object disposal here这里的对象处理有什么问题
【发布时间】:2014-09-16 14:54:32
【问题描述】:

我有一些这样的代码。

using (StreamWriter sw = new StreamWriter(@"c:\SomeFile.txt"))
{
    using (IDataReader reader = SomeMethodThatReturnsADataReader())
    {
        while (reader.Read())
        {
            // using sw and reader here
        }
    }

    sw.Close();
}

代码分析报告以下警告。

CA2202 不要多次处理对象对象“sw”可以是 方法中不止一次处理。为了避免产生 System.ObjectDisposedException 你不应该调用 Dispose 超过 一次在一个物体上。

我在这里做错了什么?

【问题讨论】:

  • StreamWriter.Dispose 会为您调用 Close,因此无需再次调用。

标签: .net c#-4.0 idisposable static-code-analysis


【解决方案1】:

正如我们从StreamWriter.Dispose() 看到的,Close 方法在其中被调用。

protected override void Dispose(bool disposing)
{
    try
    {
        if (this.stream != null && (disposing || (this.LeaveOpen && this.stream is __ConsoleStream)))
        {
            this.CheckAsyncTaskInProgress();
            this.Flush(true, true);
            if (this.mdaHelper != null)
            {
                GC.SuppressFinalize(this.mdaHelper);
            }
        }
    }
    finally
    {
        if (!this.LeaveOpen && this.stream != null)
        {
            try
            {
                if (disposing)
                {
                    this.stream.Close();
                }
            }
            finally
            {
                this.stream = null;
                this.byteBuffer = null;
                this.charBuffer = null;
                this.encoding = null;
                this.encoder = null;
                this.charLen = 0;
                base.Dispose(disposing);
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 2011-10-30
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    • 1970-01-01
    • 2011-12-11
    • 2011-01-22
    • 2016-04-11
    • 1970-01-01
    相关资源
    最近更新 更多