0

I'm in a bind right now trying to find the source of a problem. Our exception handling is lacking, so I'm kind of guessing on where the error is coming from. Here's my question, if a method returns an XmlTextReader object, does that object become null if it's wrapped in a try/catch/finally where the finally block does the .Close() method?

If yes, how can I dispose of those resources properly, I know there isn't a .Clone() or .Copy() method, is there another way to accomplish this? Should I even care about disposing of XmlTextReader and XmlReader objects?

Thanks

ganders
  • 7,285
  • 17
  • 66
  • 114

1 Answers1

1

You must not be closing/disposing XmlReader before returning it to the caller.

And no, Dispose/Close do not assign null to an object - they simply asks the object to release whatever resources it feels need to be released.

XmlReader GetReader()
{
   XmlRead reader = ....

   // DO NOT dispose/close reader here with 
   // reader.Dispose() or using(reader){...}

   return reader;
}

Usage:

using(var reader = GetReader()) {...}

Note that many types safeguard against access to data after Dispose called. Approach used by many classes in .Net is to fail all calls to access state of the object with ObjectDisposedException after Dispose is called.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • thanks, so do I not even care about calling the .Close() on XmlReader and XmlTextReader (s) at all? Wouldn't that cause an eventually memory leak if it's called CONSTANTLY in my application? – ganders May 17 '12 at 16:57
  • Answer updated with usage. You shoul call Dispose (somtime avaialble as Close too) on all object that implement IDispsable, but it needs to be done at approporiate time when you are done with it. I.e. you don't expcet `XmlReader.Create()` to return you object that is already disposed, do you? – Alexei Levenkov May 17 '12 at 17:03
  • I do not agree. Looking a MSDN there is no such exception "Object Disposed exception " being reaised by Close nor by Dispose. So it is simply not true. There is no side effects to calling Close then Dispose – Jonathan Alfaro Oct 20 '16 at 16:09
  • @Darkonekt not sure what you disagree with... Indeed Close/Dispose don't throw that exception, but most other methods that actually access state of the object should throw. If you want to see that behavior - try it with `MemoryStream` for example - call `Dispose` and than try to read data from the stream (from what I see it is very common problem asked on SO) – Alexei Levenkov Oct 20 '16 at 16:13
  • @AlexeiLevenkov I stand corrected. For a moment I thought you said that Close and Dispose could not be called together. My bad. – Jonathan Alfaro Oct 20 '16 at 23:04