Perhaps I shouldn't be trying this, but...
I have some code that is repeated throughout my application. Part of it exists at the beginning of a function and the rest at the end of the function. I'm getting tired of repeating myself, so I thought I'd wrap it up into a class that implements IDisposable and use the "using" statement to wrap the code of the function. Like this...
using( MyStuff stuff = new MyStuff())
{
...
}
The problem with this approach is in handling exceptions. Does anyone know of a way to detect in the Dispose method whether or not an exception was thrown? (I looked at the stack trace in the debugger and it looked normal.
) I'll also entertain any other ways of wrapping this code, as long as it's not...
MyStuff stuff = new MyStuff();
try
{
stuff.DoFirstPart();
...
stuff.DoSecondPart();
}
catch( Exception)
{
stuff.HandleException(e)
}
(It's still too much to type over and over again. What can I say? I'm lazy.
)
[1104 byte] By [
dkocur] at [2008-1-26]
Answered my own question (I thought). I can use the AppDomain ExceptionThrown and CatchingException events to know whether or not Dispose is called while an exception is being thrown (I thought).
Edited to add: Oops! I posted this before I tested it. CatchingException is fired BEFORE Dispose is called! Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaargh! Back to the drawing board...