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?????
Dispose
states that "if an object'sDispose
method is called more than once, the object must ignore all calls after the first one. The object must not throw an exception if itsDispose
method is called multiple times". msdn.microsoft.com/en-us/library/… – LukeH May 10 '10 at 14:33IDisposable
requires thatDispose
be idempotent. – cHao Oct 30 '12 at 21:52