处理对象不止一次错误。 CA2202。有没有更好的办法? [英] Dispose of object more than one time error. CA2202. Is there a better way?

查看:89
本文介绍了处理对象不止一次错误。 CA2202。有没有更好的办法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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

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

var结果= new StringBuilder();

试试
{
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);
}
}
最后
{
if(requestStream!= null)requestStream.Close();
if(responseStream!= null)responseStream.Close();复制代码
if(cpNetworkStream!= null)cpNetworkStream.Close();复制代码
}

由于requestStream和responseStream都使用ns,因此它们都将ns丢弃,因此顺序为了满足代码分析警告,我必须在finally块中注释掉最后两个close方法。但是,我真的要这样做吗????

解决方案

是的,恕我直言,您实际上应该只调用一次。 / p>

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

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


How can I ensure the following code is disposing of all objects in a better fashion? Currently, Code Analysis is telling me

Error 45 CA2202 : Microsoft.Usage : Object 'ns' can be disposed more than once in method 'CPCommunicator.GetResults(string)'. To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.: 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();
}

Since both requestStream and responseStream use ns, they both dispose of ns so in order to satisfy the code analysis warning, I have to comment out the last two close methods in the finally block. But do I really want to do this?????

解决方案

Yes, imho you really should only call it once.

Alternatively you could use the using syntax on ns, which makes the whole situation even clearer.

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

这篇关于处理对象不止一次错误。 CA2202。有没有更好的办法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆