处理对象多次错误。 CA2202。有没有更好的办法?

时间:2010-05-10 14:19:30

标签: c# dispose

如何确保以下代码以更好的方式处理所有对象?目前,Code Analysis告诉我

错误45 CA2202:Microsoft.Usage:对象'ns'可以在方法'CPCommunicator.GetResults(string)'中多次处理。为避免生成System.ObjectDisposedException,您不应在对象上多次调用Dispose:Lines:64,65

NetworkStream ns = null;
StreamWriter requestStream = null;
TextReader responseStream = null;

var results = new StringBuilder();

try
{
    ns = new NetworkStream(CreateConnection(), true);
    requestStream = new StreamWriter(ns);
    requestStream.Flush();
    responseStream = new StreamReader(ns);

    requestStream.Write(reportData);
    requestStream.Flush();
    while (responseStream.Peek() != -1)
    {
        var currentLine = responseStream.ReadLine();
        results.Append(currentLine);
        results.Append("\n");
    }
}
finally
{
    if (requestStream != null) requestStream.Close();
    if (responseStream != null) responseStream.Close();
    if (cpNetworkStream != null) cpNetworkStream.Close();
}

由于requestStream和responseStream都使用ns,因此它们都处理ns,以便满足代码分析警告,我必须注释掉finally块中的最后两个close方法。但我真的想这样做?????

2 个答案:

答案 0 :(得分:4)

是的,我真的应该只打电话一次。

或者你可以在ns上使用using语法,这使得整个情况更加清晰。

using (ns = new NetworkStream(CreateConnection(), true)) {
   ...
}

答案 1 :(得分:2)

我会重构您的代码:

using (NetworkStream ns = new NetworkStream(CreateConnection(), true))
using (StreamWriter requestStream = new StreamWriter(ns))
using (TextReader responseStream = new StreamReader(ns))
{

    var results = new StringBuilder();

    requestStream.Flush();

    requestStream.Write(reportData);
    requestStream.Flush();
    while (responseStream.Peek() != -1)
    {
        var currentLine = responseStream.ReadLine();
        results.Append(currentLine);
        results.Append("\n");
    }
}