Feel like a geek and get yourself Ema Personal Wiki for Android and Windows

25 July 2009

Please respect the IDisposable interface

A very frequently asked question about programming on the .NET compact framework is something similar to this:
My compact framework app hangs randomly when it does an HTTP request.

The Compact Framework only allows three simultaneous requests. The fourth request will have to wait until one of the other request objects is disposed. If you have time-outs or a request that blocks the application endlessly, you probably forgot to dispose the previous requests.

The solution is therefore quite simple. The GetRequestStream() and GetResponseStream() methods both return Stream objects. The Stream class implements the IDisposable interface. And, if you notice an IDisposable implementation, you should use it.
You may be lucky with a fast garbage collection, but in most cases, you won't. So, IDisposable? Please Dispose().

If you can correct the error in your own code, you are lucky. But too often I had to dig into sources of other libraries, which did not respect IDisposable implementations, let alone use it. In the case of a request or response stream, this is quite a flaw and renders the library useless for the Compact Framework.

I think libraries / frameworks should respect IDisposable interfaces when they meet one. And use them instead of blindly ignoring it. This will save a lot of people a lot of headaches.

No comments: