2017-02-05 46 views
0

我使用C#代码分析处置不止一次方法,得到了以下错误:对象“respStream”可以

Object 'respStream' can be disposed more than once in method 'QRadarPublisher.AnalyzeResponse(HttpWebResponse)'. To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.: 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

这是因为呼吁''StreamReader'处置Dispose'流为好。 ,请参阅http://stackoverflow.com/questions/1065168/does-disposing-streamreader-close-the-stream –

+0

合并这两个使用单一:'使用(var tStreamReader =新的StreamReader(webResponse.GetResponseStream())) '。 – Kalten

回答

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(); 
     } 
相关问题