Sunday, December 3, 2017

Update Drawing After Async Task Completed

Update Drawing After Async Task Completed


We all know that AutoCAD is not multi-thread-able when dealing with drawing database. But, this does not mean one cannot spin multiple threads from AutoCAD process. With the help of .NET framework, it is quite easy to kick off a few threads from AutoCAD process to do some time-consuming works (as long as the side threads do not deal with the drawing database loaded into AutoCAD), so that the AutoCADs main thread is not locked waiting for those lengthy works being completed.

With more and more computing power/resources being available in the clouds, it becomes more and more common that a drafting/designing process needs AutoCAD to grab information from remote locations (network share, remote database, cloud services...). Depending on the nature of the remote resources, the time to obtain data could be lengthy enough that doing it in a background thread makes much sense.

Also, in most cases, if not all, after the background thread finishes it work, wed like AutoCAD responds properly according to the result of the side thread, such as updating the currently opened drawing with the data processed/retrieved by the background thread.

Here is a scenario: with a drawing open in AutoCAD, user wants to check a remote data source for some information, which could takes seconds or minutes to complete; when AutoCAD gets that piece of information back, the drawing or drawings in current AutoCAD session is or are to be updated, such as updating complicated title block, creating or updating a few entities in drawing...; while AutoCAD tries to get data from the remote source, the user does not like AutoCAD UI being locked up, the user wants to continue to work with AutoCAD, at least to be able to zoom/pan..., for example.

There are some discussions can be found online on this topic. One is an article posted by ADN team member Adam Nagy. In his article, Adam shows how to use a System.Windows.Forms.Control to invoke a callback from the side thread to get back to AutoCAD main thread.

I also had an article discussing this topic a few years back, in which I used System.ComponentModel.BackgroundWorker to do work i n side thread. Id say that using BackgroundWorker is more natural choice in most cases: it allows the side processing to expose its progress, to be cancelled and provides status of completion (being cancelled, completed with or without error).

We, as AutoCAD programmers, are probably more interested in letting AutoCAD doing something accordingly after side thread is done with its work. The code in Adams article shows how to create a Line entity (or any type of Entity, for that matter). However, one would be wondering: what will happen if AutoCADs main thread is in middle of something, for example, a command is in progress when the side thread is done and calls back to the main thread? Can the callback still be abler to lock the MdiActiveDocuemnt and update it regardless AutoCAD having a command in progress?

To actually experience what could happen, I decided to give it a try. I started with AutoCAD 2012, which is still my companys working version, and then with AutoCAD 2014 and 2015. It proves AutoCAD 2015 makes things a bit differently, possibly because of the removal of FIBER, which Ill point out later.

Below is the code I used.

This is class SideWorker that does the side work and update drawing when side work finishes:

using System.ComponentModel;
using Autodesk.AutoCAD.ApplicationServices;
using CadApp = Autodesk.AutoCAD.ApplicationServices.Application;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;

namespace BackgroundThreadCallBack
{
    public class SideWorker
    {
        Document _dwg = null;
        BackgroundWorker _worker = null;
        int _runningCount;
        int _currentCount;

        public SideWorker(int runningCount)
        {
            _runningCount = runningCount;
        }

        public void StartSideWork()
        {
            _dwg = CadApp.DocumentManager.MdiActiveDocument;

            _worker = new BackgroundWorker();
            _worker.RunWorkerCompleted += SideWorker_RunWorkerCompleted;
            _worker.DoWork += SideWorker_DoWork;

            _currentCount = 0;

            _worker.RunWorkerAsync();
        }

        private void SideWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            //Simulate a long-running process that need 10 sec to complete
            System.Threading.Thread.Sleep(10000);
        }

        private void SideWorker_RunWorkerCompleted(
            object sender, RunWorkerCompletedEventArgs e)
        {
            Document doc = CadApp.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;

            //Only if user has not switched current drawing
            if (doc == _dwg)
            {
                _currentCount++;

                if (_currentCount <= _runningCount)
                {
                    AddCircle(doc, _currentCount * 10.0);
                    ed.WriteMessage(
                        " Circle "{0}" added.",
                        _currentCount);
                }
                
                if (_currentCount < _runningCount)
                {
                    _worker.RunWorkerAsync();
                }
                else
                {
                    ed.WriteMessage(
                        " {0} circle{1} added!",
                        _currentCount,
                        _currentCount > 1 ? "s" : "");

                    _worker.Dispose();
                }
            }
            else
            {
                ed.WriteMessage(
                    " Current drawing has changed!");
            }
        }

        private void AddCircle(Document dwg, double circleRadial)
        {
            using (var dlock=dwg.LockDocument())
            {
                using (var tran=dwg.TransactionManager.StartTransaction())
                {
                    var space = (BlockTableRecord)
                        tran.GetObject(
                        dwg.Database.CurrentSpaceId, 
                        OpenMode.ForWrite);

                    Circle c = new Circle();
                    c.Center = new Point3d(0.0,0.0,0.0);
                    c.Radius = circleRadial;
                    c.SetDatabaseDefaults();

                    space.AppendEntity(c);
                    tran.AddNewlyCreatedDBObject(c, true);

                    tran.Commit();
                }
            }
        }
    }
}

What the code does is to kick off a few times of background thread for a long processing work (I simply have this side thread sleep for 10 second to simulate a long computing process); when each of the processing is completed, the callback to the main AutoCAD thread will update the drawing (adding a Circle).

Here the the command class that uses the class SideWorker:

using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;

[assemblyCommandClass(typeof(BackgroundThreadCallBack.MyCommands))]

namespace BackgroundThreadCallBack
{
    public class MyCommands 
    {
        [CommandMethod("SideWork")]
        public static void RunMyCommand()
        {
            Document dwg = Application.DocumentManager.MdiActiveDocument;
            Editor ed = dwg.Editor;

            SideWorker worker = new SideWorker(5);
            worker.StartSideWork();

            ed.WriteMessage(
                " Side worker is started to create new circles. " +
                "You can continue working with current drawing...");

            Autodesk.AutoCAD.Internal.Utils.PostCommandPrompt();
        }
    }
}

I then ran the code in different condition:
  • After executing command "SideWork", let AutoCAD be idle;
  • After executing command "SideWork", start different AutoCAD command, it may or may not be completed before a background thread calls back to the main thread. 
Here is a video clip showing how AutoCAD reacts.

As one can see:
  • When AutoCAD is idle, there is no issue for side thread calling back and updating drawing. This is expected, of course.
  • When command, like "PLine", "Line" is in progress (that is, I kept picking point to draw a polyline and.or a line), the background thread callback has no problem to create circle in drawing.
  • When command "Circle" in progress (that is, I picked center point, and kept dragging the mouse to decide the radius), the background callback executed (as the command line message "Circle # added!" could be seen), but no circle being drawn by the callback, nor AutoCAD reports error.
  • When other command. such as "STRETCH" or "MOVE" on a SelectionSet of PickFirst entity or entities, the callback results are the same as when "CIRCLE" command in progress. That is, callback executed, no circle being added as the callback result, nor error raised.
Based on this experiment, it seems that we can say that if a real command in progress, which locks the document, then the side thread callback cannot lock the document to update it, in this case, AutoCAD somehow ignores the failed document locking/updating and continue. 

As for why when "PLINE" or "LINE" command allows side thread callback to update drawing, I guess is that when one keeps picking next point, the command is actually update the POLYLINE/LINE right at the point is picked, and when user hover the mouse for another point, the drawing is not actually locked. However, this is only true for AutoCAD 2014 or earlier. In AutoCAD 2015, however, with command "PLINE" or "LINE" in progress, the side thread callback could not update the drawing. See this video clip. Id think AutoCAD 2015s behaviour in this regard makes more sense. That is, if AutoCAD has a command in progress, it should not be interrupted by the completion of a side thread execution.

Therefore, we need find a way to let AutoCAD know that side work has been completed and it is time for AutoCAD to pick up the results and do something accordingly. either automatically, or with user interaction. With some erring and trying, I came to following modified class SideWorker:

using System.ComponentModel;
using Autodesk.AutoCAD.ApplicationServices;
using CadApp = Autodesk.AutoCAD.ApplicationServices.Application;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;

namespace BackgroundThreadCallBack
{
    public class SideWorker
    {
        Document _dwg = null;
        BackgroundWorker _worker = null;
        int _runningCount = 1;
        int _currentCount;
        bool _actionPending = false;
        bool _showDelayedMsg = false//Used for debugging purpose

        public SideWorker(int runningCount)
        {
            //Indicate how many times a background task
            //is to run as side thread
            _runningCount = runningCount;
        }

        public void StartSideWork()
        {
            _dwg = CadApp.DocumentManager.MdiActiveDocument;

            _worker = new BackgroundWorker();
            _worker.RunWorkerCompleted += SideWorker_RunWorkerCompleted;
            _worker.DoWork += SideWorker_DoWork;

            _currentCount = 0;

            //Start the very first background work
            _actionPending = false;
            _worker.RunWorkerAsync();
        }

        private void SideWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            //Simulate a long-running process that need 10 sec to complete
            System.Threading.Thread.Sleep(10000);
        }

        private void SideWorker_RunWorkerCompleted(
            object sender, RunWorkerCompletedEventArgs e)
        {
            Document doc = CadApp.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;

            if (!_actionPending)
            {
                //listenning Idle event each time when 
                //side thread has done its work
                Application.Idle += Application_Idle;
                _actionPending = true;
            }
        }

        private void Application_Idle(object sender, System.EventArgs e)
        {
            if (!_actionPending) return;

            //Even Application is idle, it may not be in quiescent state
            if (!Application.IsQuiescent)
            {
                if (!_showDelayedMsg)
                {
                    //Show why AutoCAD is not in quiescent state:
                    //a command is in profress
                    Document d = Application.DocumentManager.MdiActiveDocument;
                    d.Editor.WriteMessage(
                        " Command "{0}" is executing, drawing circle is delayed!",
                        d.CommandInProgress);
                    _showDelayedMsg = true
                }

                return;
            }

            _showDelayedMsg = false;

            Document doc = Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;

            //If user switches active document during side work execution
            //the side work thread will be&n

visit link download