The importance of calling .Close()

Courtesy of Andrew Westgarth, via IM, I found myself look at Visual Basic code last week. Andrew’s “designer” was having problems editing some files that made up an application that Andrew was developing…seemed that something was keeping a lock on the files such that they couldn’t be edited. I suggested a couple of things, including hard-coding the filename (avoiding use of Server.MapPath) just to see what happened.

However, after a little experimentation, it turns out that the XmlReader instance wasn’t being closed and as such was keeping a lock on the XSL/T file in question. The solution was to call the .Close() method. It’s obvious now, however sometimes whilst in thick of it, it’s very easy forget to call such methods, nobody’s perfect.

Andrew provides a full write-up over here:

***warning contains VisualBasic code***
Can’t Save your XSL/T File? Have You Closed Your XMLReader?/a>

Technorati Tags: , , , ,

6 thoughts on “The importance of calling .Close()”

  1. Hmm, kind of makes you wonder why XmlReader isn’t disposable
    using(XmlReader reader = XmlReader.Create(blah)){
    //do stuff
    }

    Would be much neater.

  2. You can also the XmlReaderSettings to do futher closing. As it is not always the Reader itself but the underlying stream which is still open.

    XmlReaderSettings xrs = new XmlReaderSettings();
    xrs.CloseInput = true;

    From MSDN
    “true to close the underlying stream or TextReader when the reader is closed; otherwise false. The default is false.”

    It does support IDispose so use those usings !

  3. You are right, XmlReader does implement IDisposable, I just created an instance of XmlReader and then hit the “.” and when Dispose() wasn’t there I assumed it wasn’t implemented; serves me right for being lazy. Sorry for any confusion.

  4. I have updated the original blog post with the tidied and improved code which makes use of the Using structure. The control’s a lot better for it. Thanks for all of your comments.

Comments are closed.