Intercepting an exception inside IDisposable.Dispose

前端 未结 11 1864
有刺的猬
有刺的猬 2020-12-13 02:07

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

using (MyWrapper wrapper = new MyWrapper())
{
           


        
11条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-13 02:56

    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 variable.

    Such pattern implemented in TransactionScope class.

提交回复
热议问题