[Mono-devel-list] reading a lot of files without closing them

A Rafael D Teixeira rafaelteixeirabr at hotmail.com
Sun Jan 11 11:35:03 EST 2004


>From: David Sheldon <dave-monolist at earth.li>
>
>My code was something like this:
>
>try {
>   XmlValidatingReader xvr = new XmlValidatingReader (new 
>XmlTextReader(filename));
>   while(!xvr.EOF)
>     xvr.Read();
>   xvr.Close();
>}
>catch (XmlSchemaException ex) {
>   // print error
>}

Well, commonly it should be coded as below, as the OBLIGATION to close the 
file is yours, because the finalizer may never be called by the gc, and even 
when it is called that may be too late anyway...

try {
   XmlValidatingReader xvr = new XmlValidatingReader (new 
XmlTextReader(filename));
   try {
     while(!xvr.EOF)
       xvr.Read();
   } finally {
     xvr.Close();
   }
}
catch (XmlSchemaException ex) {
   // print error
}

But being somewhat (some people say totally) lazy myself, I like to abuse of 
the 'using' statement, and as you pointed that  XmlValidatingReader doesn't 
implement IDisposable I just have my handy homegrown subclass:

class DXmlValidatingReader : XmlValidatingReader, IDisposable
{
  public DXmlValidatingReader(string FileName) : base(new 
XmlTextReader(FileName)) {}

  void IDisposable.Dispose() { this.Close(); }
}

And so the code becomes:

try {
  using (DXmlValidatingReader xvr = new DXmlValidatingReader (filename) ) {
    while(!xvr.EOF)
      xvr.Read();
  }
} catch (XmlSchemaException ex) {
  // print error
}

Rafael Teixeira
Brazilian Polymath
Mono Hacker since 16 Jul 2001
MonoBrasil Founding Member - Membro Fundador do MonoBrasil
English Blog: http://monoblog.blogspot.com/

_________________________________________________________________
MSN Messenger: converse com os seus amigos online.  
http://messenger.msn.com.br




More information about the Mono-devel-list mailing list