I get the warning CA2202 (Object can be disposed more than once) on the following code:
using (Stream responseStream = response.GetResponseStream())
{
if (responseStream != null)
using (var br = new BinaryReader(responseStream))
{
responseValue = br.ReadBytes(500000);
}
}
It seems like, the responseStreams Dispose is called when the BinaryReaders Dispose is called. Does the BinaryReader always call the Streams Dispose Method?
One solution would be to initialize the ResponseStream directly and let the BinaryReader take care about disposing the stream (which, of course, would only work, if the BinaryReader would dispose the stream in any situation)
Stream responseStream = response.GetResponseStream();
if(responseStream != null)
using (var br = new BinaryReader(responseStream)) //Always disposes the response stream?
[...]
I could use a try/finalize instead of the outer using statement to get something like this:
Stream responseStream = null;
try
{
responseStream = response.GetResponseStream();
if (responseStream != null)
using (var br = new BinaryReader(responseStream))
{
responseValue = br.ReadBytes(500000);
}
}
finally
{
if(stream != null)
stream.Dispose;
}
This isn't nice to look and unnecessary, when the BinaryReader always disposes the stream. Is there a better / preferred solution to solve this kind of problem?
IDisposable.Dispose(), "If an object's Dispose method is called more than once, the object must ignore all calls after the first one. - which means that this is supposed to be a non-issue (other than the fact that you might have disposed it in one place and then continue to attempt to use it later on, which is a different issue). - Matthew Watson