Is it possible to determine if code is currently executing in the context of a finally
handler as a result of an exception being thrown? I\'m rather fond of usi
Why not simply dispose from inside a try { }
block at the very end, and not use a finally at all? This seems to be the behavior you're looking for.
This also seems more realistic in terms of how others might use your class. Are you sure that everybody who ever uses it will never want to dispose in the case of an exception? Or should this behavior be handled by the consumer of the class?
The best I can come up with would be:
using (var scope = MyScopedBehavior.Begin())
{
try
{
//Do stuff with scope here
}
catch(Exception)
{
scope.Cancel();
throw;
}
}
Of course, scope.Cancel()
would make sure nothing happens in Dispose()