This question describes the same scenario as in CA2202, how to solve this case , but it is not about how to fix the code, about why there is a problem in the first place.
The following code:
using (Stream stream = obtainStreamObject()) { using (var reader = new XmlTextReader(stream)) {
calls Stream.Dispose() , called twice. First, the using block fails, which calls XmlTextReader.Dispose() , which in turn calls Stream.Dispose() . Then the using outer block is compressed and Stream.Dispose() is called again.
So I need to wrap Stream in using , but not wrap XmlTextReader in using , despite the fact that both of them implement IDisposable .
This gives warning CA2202
Do not place objects several times. The stream object can be deleted more than once in the Method Name (Independently) method. To avoid throwing a System.ObjectDisposedException, you should not throw Dispose more than once on an object.
Ok, he says the second Dispose() can give an ObjectDisposedException . How does that make sense? Why should I implement Dispose() so that when I call it a second time, it will throw an exception instead of just doing nothing?
source share