Mehdi wrote:
> On Wed, 14 Jun 2006 22:47:55 +0200, Markus Stoeger wrote:
>
> Dispose() should not throw any exception. This is clearly mentionned
> in the IDisposable documentation. I suppose that this rule has been
> put in place to solve the exact same problem you are facing now.
I couldn't find the place on msdn where they say that Dispose shouldn't
throw? See [1] in the remarks section, it says:
Dispose _can throw an exception_ if an error occurs because a resource
has already been freed and Dispose had not been called previously.
... that's at least one reason why Dispose should be allowed to throw.
If those exceptions are swallowed, it can actually lead to resource
leaks over time without anyone noticing why. No good imho.
I came up with the following simple piece of code. It does nested
try/finally blocks automatically using recursion. I think that'll do a
good job, making sure that _everything_ gets disposed without hiding the
exception in case something throws.
Call with Disposer.Dispose(obj1, obj2, obj3);
public sealed class Disposer {
private Disposer() {}
public static void Dispose(params IDisposable[] disposees) {
Dispose(disposees, 0);
}
private static void Dispose(IDisposable[] disposees, int index) {
if (index < disposees.Length) {
try {
IDisposable disposee = disposees[index];
if (disposee != null) {
disposee.Dispose();
}
}
finally {
Dispose(disposees, index + 1);
}
}
}
}
thanks,
Max
[1]
http://msdn.microsoft.com/library/de...sposetopic.asp