对象'respStream'可以在方法中多次处理

时间:2017-02-05 19:12:32

标签: c#

我正在使用C#代码分析并收到以下错误:

  

对象'respStream'可以在方法'QRadarPublisher.AnalyzeResponse(HttpWebResponse)'中多次处理。为避免生成System.ObjectDisposedException,不应在对象上多次调用Dispose:Lines:116

这是代码:

using (Stream respStream = webResponse.GetResponseStream())
{   
    using (var tStreamReader = new StreamReader(respStream))
    {

        try
        {
            //My Code
        }
        catch (Exception ex)
        {
            //My Code
        }
     }
}//The error is for this brace

如何解决错误?

1 个答案:

答案 0 :(得分:2)

你总是可以摆脱第一个'使用'块:

        Stream respStream = null;
        try
        {
            respStream = webResponse.GetResponseStream();
            using(var tStreamReader = new StreamReader(respStream))
            {
    // If this line is reached you don't need to call Dispose manually on respStream
    // so you set it to null

               respStream = null; 
               try
               {
                 //My Code
               }
               catch(Exception ex)
               {
                //My Code
               }
            }
        }
        finally
        {
// if respStream is not null then the using block did not dispose it
// so it needs to be done manually:
           if(null != respStream)
               respStream.Dispose();
        }
相关问题