Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercepting an exception inside IDisposable.Dispose

In the IDisposable.Dispose method is there a way to figure out if an exception is being thrown?

using (MyWrapper wrapper = new MyWrapper()) {     throw new Exception("Bad error."); } 

If an exception is thrown in the using statement I want to know about it when the IDisposable object is disposed.

like image 813
James Newton-King Avatar asked Oct 20 '08 22:10

James Newton-King


People also ask

What happens if you dont dispose IDisposable?

IDisposable is usually used when a class has some expensive or unmanaged resources allocated which need to be released after their usage. Not disposing an object can lead to memory leaks.

Does using dispose on exception?

Dispose() does not get called in the attached code. Further more the exception that is thrown is not handled and the program blows up.

What is IDisposable interface in C implement the Dispose method?

The Dispose method is automatically called when a using statement is used. All the objects that can implement the IDisposable interface can implement the using statement. You can use the ildasm.exe tool to check how the Dispose method is called internally when you use a using statement.

Is IDisposable called automatically?

Dispose() will not be called automatically. If there is a finalizer it will be called automatically. Implementing IDisposable provides a way for users of your class to release resources early, instead of waiting for the garbage collector.


2 Answers

You can extend IDisposable with method Complete and use pattern like that:

using (MyWrapper wrapper = new MyWrapper()) {     throw new Exception("Bad error.");     wrapper.Complete(); } 

If an exception is thrown inside the using statement Complete will not be called before Dispose.

If you want to know what exact exception is thrown, then subscribe on AppDomain.CurrentDomain.FirstChanceException event and store last thrown exception in ThreadLocal<Exception> variable.

Such pattern implemented in TransactionScope class.

like image 63
Kelqualyn Avatar answered Sep 22 '22 15:09

Kelqualyn


No, there is no way to do this in the .Net framework, you cannot figure out the current-exception-which-is-being-thrown in a finally clause.

See this post on my blog, for a comparison with a similar pattern in Ruby, it highlights the gaps I think exist with the IDisposable pattern.

Ayende has a trick that will allow you to detect an exception happened, however, it will not tell you which exception it was.

like image 42
Sam Saffron Avatar answered Sep 20 '22 15:09

Sam Saffron