This question describes the same scenario as in CA2202, how to solve this case but it's not about how to fix the code, it's about why there's a problem in the first place.
The following code:
using (Stream stream = obtainStreamObject())
{
using (var reader = new XmlTextReader(stream))
{
//do something with XmlTextReader
}
}
causes Stream.Dispose()
called twice. First the inner using
block collapses which calls XmlTextReader.Dispose()
which in turn causes Stream.Dispose()
. Then the outer using
block collapses and Stream.Dispose()
is called again.
So I have to wrap Stream
into using
but not wrap XmlTextReader
into using
despite they both implement IDisposable
.
This yields CA2202 warning
Do not dispose objects multiple times Object 'stream' can be disposed more than once in method 'MethodName(whatever)'. To avoid generating a System.ObjectDisposedException you should not call Dispose more than one time on an object.
Okay, it says that the second Dispose()
might yield ObjectDisposedException
. How does this make sense? Why would I implement Dispose()
such that when it's called for the second time it would throw an exception instead of just doing nothing?