Is there a need to call Transaction.Abort() when catching exception?

Is there a need to call Transaction.Abort() when catching exception?

soonhui
Advisor Advisor
544 Views
1 Reply
Message 1 of 2

Is there a need to call Transaction.Abort() when catching exception?

soonhui
Advisor
Advisor

This is my current code.

 

      protected void Write(Action<Transaction> action)
      {
          using (ACADDocument.LockDocument())
          {
              using (var ts = ACADDatabase.TransactionManager.StartTransaction())
              {
                  try
                  {
                      action(ts);
                      ts.Commit();
                  }
                  catch (Exception ex)
                  {
                      // log the error
                     ts.Abort();  // is this necessary at all?
                     throw;
                  }
              }
          }
      }

 

But I wonder whether there is a need to call Transaction.Abort() in the catch, because if a transaction is not committed then it's automatically aborted ( or is it?)

 

If that's the case, then why do we need Abort() method at all?


Can anyone clarify on this?

##########

Ngu Soon Hui

##########

I'm the Benevolent Dictator for Life for MiTS Software. Read more here


I also setup Civil WHIZ in order to share what I learnt about Civil 3D
0 Likes
Accepted solutions (1)
545 Views
1 Reply
Reply (1)
Message 2 of 2

ActivistInvestor
Mentor
Mentor
Accepted solution

No need to call Abort(), and no need for try/finally if that's only to call Abort().

 

When a transaction is disposed (as it is in your example, because it is managed by using()), it will abort if it has not already been committed.

 

So the basic pattern usually is:

 

using(var tr = doc.TransactionManager.StartTransaction()
{
   // use Transaction here, if an exception is thrown,
   // the call to Commit() never happens, the transaction
   // is disposed, and it aborts.

   tr.Commit();
}

 

 

You generally don't need to call Abort() if you use the Dispose pattern via using(). I would have to search long and hard to find a call to Abort() in the code I've written over the past 10 years.