Auto Commit

Auto Commit

SENL1362
Advisor Advisor
3,313 Views
18 Replies
Message 1 of 19

Auto Commit

SENL1362
Advisor
Advisor

I'd like you to comment on an issue with is bordering me for some time.

I’ve notice on several posts from Autodesk that Commit is faster than Abort, so why isn't Commit the default.

 

 

For instance when this happens i suppose Abort is issued from the Dispose -- Implicitly called by Using.

               using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    if (1==1)
                        return;

                    //...
                    tr.Commit();
                }

To avoid a lot of if/then blocks one could implement:

 

                using (MyTransaction tr = new MyTransaction(db,true))
                 {
//...
//if ("YouRealyWantToAbort".Length > 0) // tr.AutoCommit = false; if (1 == 1) return; //... tr.Commit(); } //... public class MyTransaction : IDisposable { private bool disposed = false; private Database DB { get; set; } private Transaction TR { get; set; } public bool AutoCommit { get; set; } public MyTransaction(Database db, bool autoCommit=true) { DB = db; TR = db.TransactionManager.StartTransaction(); AutoCommit = autoCommit; //... protected virtual void Dispose(bool disposing) { if (!disposed) { if (disposing) { if (TR!=null && AutoCommit) TR.Commit(); TR.Dispose(); TR = null; DB = null; } disposed = true; } } //...

 

- I couldn't find any way to find out if a transaction already is Committed or Aborted.

- Why wouldn't Autodesk added the AutoCommit feature?

 

 

 

 

 

 

 

0 Likes
Accepted solutions (1)
3,314 Views
18 Replies
Replies (18)
Message 2 of 19

jeff
Collaborator
Collaborator

That's typically the pattern

  • Start Transaction
  • Make Changes
  • Commit or RollBack
  • End Transaction

I guess its thought easier to code by allowing the "fall through" path default to RollBack, or better not to change database vs change database if neither is called.

 

Not sure if can tell if aborted or committed but IsDisposed should be true if either were called.

 

 

 

 

 

 

 

 

 

You can also find your answers @ TheSwamp
0 Likes
Message 3 of 19

kerry_w_brown
Mentor
Mentor

I haven't thought it through completely , but are you proposing commiting the transaction regardless of the result of the process.

You'd better hope your users don't know where you live !

 


// Called Kerry or kdub in my other life.

Everything will work just as you expect it to, unless your expectations are incorrect. ~ kdub
Sometimes the question is more important than the answer. ~ kdub

NZST UTC+12 : class keyThumper<T> : Lazy<T>;      another  Swamper
0 Likes
Message 4 of 19

SENL1362
Advisor
Advisor
of course not, on the contrary i want control over the closure. It's by default RollBack unless you Commit. In a substantial part of my code i use transactions for queries in which case in doesn't matter if the transaction is closed by RollBack or Commit. But Autodesk repeatedly has written Commit is faster, therefore a method to influence the default closure would be welcomed.
If gives me more freedom in the Using code block.
I also see these Auto Commit patterns in other Database related software.

P.s. I hope I can still ask questions, stupid or not, without worrying where a live 🙂
0 Likes
Message 5 of 19

SENL1362
Advisor
Advisor

It's obvious that Autodesk defaults to RollBack but in query transaction it doesn't matter how the closure is done, so a method to choose for the most efficient would be nice.
Dispose is implicitly called when leaving the Using block, thus the closure is already done and therefore to late.

At first i thought StartOpenCloseTransaction might be useful for query transactions but i quess it's not different to StartTransaction.
Also ran into trouble when used in nested situations.

0 Likes
Message 6 of 19

Balaji_Ram
Alumni
Alumni

Hi,

 

I do not think there is a way to know if the transaction has been aborted or committed already.

 

A way to always commit regardless of multiple return statements in a block of code could be enclose them in a

try-catch-finally and commit as shown here :

 

Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
Database db = HostApplicationServices.WorkingDatabase;
Transaction tr = db.TransactionManager.StartTransaction();
try
{
    // Code
    return;

    // Some more code
    //...
    return;

    // Some more code
    //...
}
catch (System.Exception ex)
{
    ed.WriteMessage(ex.Message);
}
finally
{
    // Always commit.
    tr.Commit();
}

Regards,

 

Balaji



Balaji
Developer Technical Services
Autodesk Developer Network

Message 7 of 19

SENL1362
Advisor
Advisor

Balaji thank you for you're comments on this, I'll going to test it in my code.

 

It's relatively easy to overcome the problem of not knowing that Commit/RollBack has been done:

 

tr.Commit();

tr=null;

 

...

 

Finally

{

   if (tr != null)

     tr.Commit();

 

 

0 Likes
Message 8 of 19

FRFR1426
Collaborator
Collaborator

If you do not open any object as write, there is nothing to rollback and the Commit and Rollback operation will take the same time to execute.

Maxence DELANNOY
Manager
Add-ins development for Autodesk software products
http://wiip.fr
0 Likes
Message 9 of 19

SENL1362
Advisor
Advisor
Maxence, That's useful information as well. Thanks.
0 Likes
Message 10 of 19

FRFR1426
Collaborator
Collaborator

However, this test seems to indicate that I'm wrong. It's strange because AutoCAD should not record undo data for object opened as read.

Maxence DELANNOY
Manager
Add-ins development for Autodesk software products
http://wiip.fr
0 Likes
Message 11 of 19

FRFR1426
Collaborator
Collaborator
Accepted solution

I've done my own tests with this code:

 

public static ObjectId GetLastCircle(bool commit)
{
    ObjectId cirId = ObjectId.Null;
    Database db = HostApplicationServices.WorkingDatabase;
    using (Transaction tr = db.TransactionManager.StartTransaction())
    {
        BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
        BlockTableRecord btr = (BlockTableRecord)tr.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead);
        foreach (ObjectId id in btr)
        {
            DBObject obj = tr.GetObject(id, OpenMode.ForRead);
            if (obj is Circle)
                cirId = obj.ObjectId;
        }
        Stopwatch sw = Stopwatch.StartNew();
        if (commit)
            tr.Commit();
        else
            tr.Abort();
        Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
        ed.WriteMessage("Time elapsed when commit is {0}: {1} ms\n", commit, sw.ElapsedMilliseconds);
    }
    return cirId;
}

[CommandMethod("READANDCOMMIT")]
public static void ReadAndCommit()
{
    GetLastCircle(commit: true);
}

[CommandMethod("READBUTNOTCOMMIT")]
public static void ReadButNotCommit()
{
    GetLastCircle(commit: false);
}

I've done 10 READANDCOMMIT and the average ellapsed time is 93.6 ms. I then restarted AutoCAD and run 10 times READBUTNOTCOMMIT. The average ellapsed time is 112.4 ms. So there is a 20% penalty when using Abort instead of Commit when you only open object as read.

 

Maxence DELANNOY
Manager
Add-ins development for Autodesk software products
http://wiip.fr
Message 12 of 19

SENL1362
Advisor
Advisor

My Results on you're slightly modified code:

Command: READANDCOMMIT
Time elapsed when commit is True: 3 ms

Command: READBUTNOTCOMMIT
Time elapsed when commit is False: 9 ms

 

 

           Stopwatch sw = Stopwatch.StartNew();
            using (MyTransaction tr = new MyTransaction(db))
            {
                tr.AutoCommit = commit;
                BlockTable bt = tr.TR.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                BlockTableRecord btr = (BlockTableRecord)tr.TR.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForRead);
                foreach (ObjectId id in btr)
                {
                    DBObject obj = tr.TR.GetObject(id, OpenMode.ForRead);
                    if (obj is Circle)
                        cirId = obj.ObjectId;
                }
               
                //if (commit)
                //    tr.Commit();
                //else
                //    tr.Abort();
            }
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            ed.WriteMessage("Time elapsed when commit is {0}: {1} ms\n", commit, sw.ElapsedMilliseconds);
            return cirId;

 

public class MyTransaction : IDisposable
    {
        private bool disposed = false;
        private Database DB { get; set; }
        public Transaction TR { get; private set; }
        public bool AutoCommit { get; set; }


        public MyTransaction(Database db, bool autoCommit = true)
        {
            DB = db;
            TR = db.TransactionManager.StartTransaction();
            AutoCommit = autoCommit;
        }

        public void Commit()
        {
            if (TR != null)
                TR.Commit();
            TR = null;
        }

        public void Abort()
        {
            if (TR != null)
                TR.Abort();
            TR = null;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!disposed)
            {
                if (disposing)
                {
                    if (TR != null && AutoCommit)
                        TR.Commit();
                    TR.Dispose();
                    TR = null;
                    DB = null;
                }
                disposed = true;
            }
        }

        ~MyTransaction() 
        { 
            Dispose(false); 
        }


    }

 

0 Likes
Message 13 of 19

SENL1362
Advisor
Advisor

Unfortunately we cannot yet add Fields and Methods to Classes except for Dynamics.
It would make code more elegant.

0 Likes
Message 14 of 19

FRFR1426
Collaborator
Collaborator

You are including the loop on the database objects in your time measurement. I think we need to only measure the time passed in the Abort or Commit method.

Maxence DELANNOY
Manager
Add-ins development for Autodesk software products
http://wiip.fr
0 Likes
Message 15 of 19

SENL1362
Advisor
Advisor

Sorry for the delay, work.. work.. work...

You are absolutely right regarding the absolute times, however more important are the diferences between Commit and Abort.

 

These are the new numbers

READANDCOMMIT:: 0 to 15 ms

READBUTNOTCOMMIT:: 7 to 25 ms

 

So the conclusion based on youre code  is that it is important to Commit whenever it is possible.

 

 

              ...
              sw = Stopwatch.StartNew();
                //if (commit)
                //    tr.Commit();
                //else
                //    tr.Abort();
            }
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            ed.WriteMessage("Time elapsed when commit is {0}: {1} ms\n", commit, sw.ElapsedMilliseconds);
            return cirId;

 

0 Likes
Message 16 of 19

jeff
Collaborator
Collaborator

The reason abort takes longer is cause it reads undo and then regens graphics for each entity instead waiting till the end.

 

It is all in the docs and by starting a transaction will start a undo mark in file and opening objects with ObjectId.Open will get rolled back with transaction also.

 

http://www.theswamp.org/index.php?topic=44037.msg493301#msg493301

 

I think Autodesk did the right thing and  Abort takes longer but that should only really happen when it error outs before reaches Commit call.

 

You can add code contracts etc... to staticlly check if a transaction is started that commit is called, and why people use them outside of methods marked with CommandMethod Attribute I have never understood.

 

Other than an event your code will always start and end in a command method.

 

 

 

You can also find your answers @ TheSwamp
Message 17 of 19

SENL1362
Advisor
Advisor

Hello Jeff,
Appreciate you're comment as well, some is known and you're thoughts about the commands are interesting.


I've done some more testing,
TransactionClosingTime=f(Read/Write,Commit/Abort)
which makes me more convinced the need to have  better control over the way the transaction is closed, with simple code construction, because .NET.

 

In none of the tests below is the Database changed.

Screenshot_2.png

 

With the "modified" transaction  Type i can now easilly decide for each part how to close the transaction

- with using control

- without ugly if/else blocks

 

 

Note the convenient abbreviation for AutoCommit (ac)

using (AutoCommitTransaction acTr = new AutoCommitTransaction(db))
{
   var tr = acTr.TRaction;
   BlockTableRecord ms = (BlockTableRecord)tr.GetObject(...)

   acTr.AutoCommit=true;    //quit as fast as possible
   //bail out early
   if (...)
      return;

   acTr.AutoCommit=false; //don't alter anything when something is wrong
   if (...)
      throw new ...
   ...

   //Commit/Abort handled by the using of autoCommitTr
}

 

 

 

 

 

 

Message 18 of 19

FRFR1426
Collaborator
Collaborator

Please note that even if no object is opened for write, systems variables can be modified. If there is an user input occurring into the transaction, the user can pan or zoom and this changes some variables like VIEWSIZE. So Abort and Commit will not have the same effect. Abort will restore the view to its initial state, whereas with Commit the view will stay where the user has left it.

Maxence DELANNOY
Manager
Add-ins development for Autodesk software products
http://wiip.fr
0 Likes
Message 19 of 19

SENL1362
Advisor
Advisor
Good point, therefore keep control and default to Commit.
0 Likes