Intercepting an exception inside IDisposable.Dispose

前端 未结 11 1857
有刺的猬
有刺的猬 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:50

    Now, in 2017, this is the generic way to do it, incl handling rollback for exceptions.

        public static T WithinTransaction(this IDbConnection cnn, Func fn)
        {
            cnn.Open();
            using (var transaction = cnn.BeginTransaction())
            {
                try
                {
                    T res = fn(transaction);
                    transaction.Commit();
                    return res;
                }
                catch (Exception)
                {
                    transaction.Rollback();
                    throw;
                }
                finally
                {
                    cnn.Close();
                }
            }
        }
    

    and you call it like this:

            cnn.WithinTransaction(
                transaction =>
                {
                    var affected = ..sqlcalls..(cnn, ...,  transaction);
                    return affected;
                });
    

提交回复
热议问题