000

Index Labels

Plugging Asynchronous Task Execution Into AutoCAD

.
There may be times when a custom AutoCAD application needs to perform a lengthy execution that mainly deals with external resources, such as checking remote resources for available update to certain applications/data. If the lengthy execution has nothing to do with drawing document/database opened in current AutoCAD session, it can be run in a separate thread other than AutoCAD UI thread, so AutoCAD would not be in a non-responsive state while the lengthy execution is running.

In this article, I demonstrate a component - AsyncTaskManager - that runs lengthy processes in background thread. With this component, a developer would focus his/her effort on developing the task itself, which would be executed in background thread once being plugged into the component.

I used a Windows system tray icon (System.Windows.Form.NotifyIcon) to prompt user for the start/end of each task being executed asynchronously.

Let take a look to the code.

Firstly, I defined an Interface ITask that represents a unified interface of possible tasks that can be executed by the AsyncTaskManager:

namespace StartupAsyncTask
{
    public interface ITask
    {
        string TaskName { get; }
        string CompletionMessage { get; }
        object ResultData { get; }
        bool Successful { get; }
        void Execute();
    }
}

In this interface, property TaskName is used to identify a task being executed and also used as balloon message title of system tray icon. CompletionMessage is used as balloon message text of the system tray icon. ResultData is possible data generated by the task during its execution.

Then, here is a class that actually dispatch tasks into background thread and activate system tray icon to give user feedback on the task execution (started/ended):

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
 
namespace StartupAsyncTask
{
    public class AsyncTaskRunner : IDisposable
    {
        private int _currentTaskCount = 0;
        private List<ITask> _tasks = null;
 
        private NotifyIcon _notifyIcon = null;
        private System.ComponentModel.BackgroundWorker _backWorker = null;
        private System.Timers.Timer _timer = null;
 
        public AsyncTaskRunner()
        {
 
        }
 
        public event System.EventHandler AllTasksCompleted;
        public event TaskCompletedEventHandler TaskCompleted;
 
        public void ExecuteTasks(List<ITask> tasks)
        {
            //Create system tray icon
            CreateNotifyIcon();
 
            _tasks = tasks;
            if (_tasks.Count == 0) return;
 
            //Run first task
            _currentTaskCount = 0;
            RunTask(_tasks[_currentTaskCount]);
        }
 
        private void RunTask(ITask task)
        {
            OnTaskStarted(task);
 
            //Configure BackgroundWorker component
            _backWorker = new System.ComponentModel.BackgroundWorker();
            _backWorker.DoWork += 
                new System.ComponentModel.DoWorkEventHandler(backWorker_DoWork);
            _backWorker.RunWorkerCompleted += 
                new System.ComponentModel.RunWorkerCompletedEventHandler(
                    backWorker_RunWorkerCompleted);
 
            //Run task as backgroud thread
            _backWorker.RunWorkerAsync(task);
        }
 
        private void backWorker_RunWorkerCompleted(
            object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            if (!e.Cancelled)
            {
                ITask task = e.Result as ITask;
                OnTaskComleted(task);
 
                if (TaskCompleted != null)
                {
                    TaskCompleted(this, 
                        new TaskCompletedEventArgs(task.TaskName, task.ResultData));
                }
            }
 
            _backWorker.DoWork -= 
                new System.ComponentModel.DoWorkEventHandler(backWorker_DoWork);
            _backWorker.RunWorkerCompleted -= 
                new System.ComponentModel.RunWorkerCompletedEventHandler(
                    backWorker_RunWorkerCompleted);
            _backWorker.Dispose();
            _backWorker = null;
        }
 
        private void backWorker_DoWork(
            object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            ITask task = e.Argument as ITask;
            task.Execute();
            e.Result = task;
        }
 
        private void OnTaskStarted(ITask task)
        {
            ShowNotifyIconBalloon(
                task.TaskName, "Start " + task.TaskName + "...", 2000, true);  
        }
 
        private void OnTaskComleted(ITask task)
        {
            _currentTaskCount++;
 
            ShowNotifyIconBalloon(
                task.TaskName, task.CompletionMessage, 2000,task.Successful);
 
            //Wait 2 seconds to either go to next task, or dispose the NotifyIcon
            _timer = new System.Timers.Timer();
            _timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
            _timer.Interval = 2000;
            _timer.Start();
 
        }
 
        void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            _timer.Stop();
            _timer.Dispose();
 
            if (_currentTaskCount < _tasks.Count)
            {
                //Run next task
                RunTask(_tasks[_currentTaskCount]);
            }
            else
            {
                if (AllTasksCompleted != null)
                {
                    AllTasksCompleted(this, EventArgs.Empty);
                }
            }
        }
 
        private void CreateNotifyIcon()
        {
            _notifyIcon = new NotifyIcon();
            _notifyIcon.Icon=
                (Icon)Properties.Resources.ResourceManager.GetObject("AcadStartUp");
            _notifyIcon.Visible=true;
        }
 
        private void ShowNotifyIconBalloon(
               string title, string text, int timeout, bool successful)
        {
            _notifyIcon.BalloonTipTitle = title;
            _notifyIcon.BalloonTipText = text;
            if (successful)
            {
                _notifyIcon.BalloonTipIcon = System.Windows.Forms.ToolTipIcon.Info;
            }
            else
            {
                _notifyIcon.BalloonTipIcon = System.Windows.Forms.ToolTipIcon.Error;
            }
            _notifyIcon.ShowBalloonTip(timeout);
        }
 
 
        public void Dispose()
        {
            if (_notifyIcon != null)
            {
                _notifyIcon.Dispose();
            }
        }
    }
 
    public delegate void TaskCompletedEventHandler(
                object sendr, TaskCompletedEventArgs e);
 
    public class TaskCompletedEventArgs : System.EventArgs
    {
        private object _outputData;
        private string _taskName;
 
        public TaskCompletedEventArgs(string taskName, object outputData)
        {
            _taskName = taskName;
            _outputData = outputData;
        }
 
        public string TaskName
        {
            get { return _taskName; }
        }
 
        public object OutputData
        {
            get { return _outputData; }
        }
    }
}

As you can see, this class implements IDisposable interface, so that the System.Windows.Forms.NotifyIcon object used in this class can be disposed properly. The only public method ExecuteTasks() takes a list of ITask as argument, and execute the the tasks one by one sequentially. However, the sequence of execution i s not done in a "foreach..." or "while..." loop, because each task is sent to a background thread for the execution. I used RunWorkerCompleted event handler to count tasks being executed and start execution on next task. Also, in order for the system tray icon to have enough time to show a balloon message to user, I user a timer to display next task for a couple of seconds. This class will raise an event when each task execution is completed and raise another event when all tasks are completed.

Now the class AsyncTaskManager pulls things together:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
 
namespace StartupAsyncTask
{
    public class AsyncTaskManager
    {
        private List<ITask> _tasks = null;
        private AsyncTaskRunner taskRunner = null;
        private Dictionary<string, object> _resultData = null;
 
 
        public AsyncTaskManager()
        {
            InitializeTasks();
        }
 
        public event System.EventHandler TasksExecutionCompleted;
 
        public Dictionary<string, object> ResultData
        {
            get { return _resultData; }
        }
 
        public void RunTasks()
        {
            _resultData = new Dictionary<string, object>();
 
            taskRunner = new AsyncTaskRunner();
            taskRunner.TaskCompleted += 
                new TaskCompletedEventHandler(taskRunner_TaskCompleted);
            taskRunner.AllTasksCompleted += 
                new EventHandler(taskRunner_AllTasksCompleted);
 
            taskRunner.ExecuteTasks(_tasks);
        }
 
        public void RunTasks(List<ITask> tasks)
        {
            _tasks = tasks;
            RunTasks();
        }
 
        private void taskRunner_TaskCompleted(
            object sendr, TaskCompletedEventArgs e)
        {
            //Do something if necessary
        }
 
        private void taskRunner_AllTasksCompleted(
            object sender, EventArgs e)
        {
            taskRunner.Dispose();
 
            foreach (ITask t in _tasks)
            {
                if (t.ResultData != null)
                {
                    _resultData.Add(t.TaskName, t.ResultData);
                }
            }
 
            //Bubble up the event to AutoCAD calling process
            if (TasksExecutionCompleted != null)
            {
                TasksExecutionCompleted(this, EventArgs.Empty);
            } 
        }
 
        private void InitializeTasks()
        {
            //Get a task lists, hard coded here, 
            //It can also be set up in declarative style,
            //such as in acad.exe.config
            _tasks = new List<ITask>();
            _tasks.Add(new Task1());
            _tasks.Add(new Task2());
            _tasks.Add(new Task3());
        }
    }
}

This class simply holds tasks to be executed, calls AsyncTaskRunner's ExecuteTasks() method and stores possible data generated in task execution (in a Dictionary with task name as key).

Now let define a few tasks that will be executed by AsyncTaskManager. This what a developer can now focus his/her effort on without worrying how to do things in background thread.

Here are 3 ITask classes. For the simplicity, The classes do not do real thing other than to put the thread into sleep for a few seconds (to mimic a possible real world process that may takes a while to complete - that is the purpose to use background thread in most cases, right?).

using System.Text;
using System.Threading;
 
namespace StartupAsyncTask
{
    public class Task1 : ITask
    {
        private StringBuilder _errMsg = new StringBuilder();
        private bool _successful = false;
 
        public string TaskName
        {
            get { return "Check Available Update"; }
        }
 
        public string CompletionMessage
        {
            get { return _errMsg.ToString(); }
        }
 
        public bool Successful
        {
            get { return _successful; }
        }
 
        public object ResultData
        {
            get { return null; }
        }
 
        public void Execute()
        {
            _errMsg.Length = 0;
            _successful = true;
 
            //Do something
            DoTask();
        }
 
        private void DoTask()
        {
            Thread.Sleep(5000);
            _successful = false;
            _errMsg.Append("This startup task execution has failed!");
        }
    }
}


using System.Text;
using System.Threading;
 
namespace StartupAsyncTask
{
    public class Task2 : ITask
    {
        private StringBuilder _errMsg = new StringBuilder();
        private bool _successful = false;
 
        public string TaskName
        {
            get { return "Send Data To XXX Service"; }
        }
 
        public string CompletionMessage
        {
            get { return _errMsg.ToString(); }
        }
 
        public bool Successful
        {
            get { return _successful; }
        }
 
        public object ResultData
        {
            get { return null; }
        }
 
        public void Execute()
        {
            _errMsg.Length = 0;
            _successful = true;
 
            //Do something
            DoTask();
        }
 
        private void DoTask()
        {
            Thread.Sleep(5000);
            _errMsg.Append("This startup task has been completed successfully!");
        }
    }
}

using System.Collections.Generic;
using System.Text;
using System.Threading;
 
namespace StartupAsyncTask
{
    public class Task3 : ITask
    {
        private StringBuilder _errMsg = new StringBuilder();
        private bool _successful = false;
        private List<string> _returnData = null;
 
        public string TaskName
        {
            get { return "Retrieve Google Map Data"; }
        }
 
        public string CompletionMessage
        {
            get { return _errMsg.ToString(); }
        }
 
        public bool Successful
        {
            get { return _successful; }
        }
 
        public object ResultData
        {
            get { return _returnData; }
        }
 
        public void Execute()
        {
            _errMsg.Length = 0;
            _successful = true;
 
            _returnData = new List<string>();
 
            //Do something
            DoTask();
        }
 
        private void DoTask()
        {
            Thread.Sleep(10000);
            _errMsg.Append("This startup task has been completed successfully!");
 
            _returnData.AddRange(new string[] { "AAAA", "BBBB", "CCCC" });
        }
    }
}

Ideally, these ITask classes would be in their own project(s) and references the main project where ITask interface is in. So, if a new ITask class can be developed independently without affecting existing tasks.

Now, let take a look how to put the code in action in AutoCAD:

using System;
 
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Runtime;
 
[assembly: ExtensionApplication(typeof(StartupAsyncTask.MyCommands))]
 
namespace StartupAsyncTask
{
    public class MyCommands : IExtensionApplication
    {
        #region IExtensionApplication Members
 
        private static frmGoogleData _frm = null;
 
        public void Initialize()
        {
            //If there are tasks to run on startup
            //RunAsyncTasks();
        }
 
        public void Terminate()
        {
 
        }
 
        #endregion
 
        [CommandMethod("DoTasks",CommandFlags.Session)]
        public static void RunAsyncTasks()
        {
            Document doc = Application.DocumentManager.MdiActiveDocument;
 
            if (doc != null)
            {
                doc.Editor.WriteMessage("\nStart tasks execution...\n");
            }
 
            try
            {
                AsyncTaskManager taskManager = new AsyncTaskManager();
                taskManager.TasksExecutionCompleted += 
                    new EventHandler(taskManager_TasksExecutionCompleted);
 
                //Run default tasks
                taskManager.RunTasks();
 
                //Or ===================================================
                //List<IStartupTask> tasks = new List<IStartupTask>();
                //tasks.Add(new Task1());
                //tasks.Add(new Task2());
                //taskManager.RunTasks(tasks);
                //======================================================
            }
            catch (System.Exception ex)
            {
                doc = Application.DocumentManager.MdiActiveDocument;
                if (doc != null)
                {
                    doc.Editor.WriteMessage(
                        "\nInitializing process error:\n" + ex.Message + "\n");
                }
            }
        }
 
        [CommandMethod("TaskData", CommandFlags.Session)]
        public static void ShowTaskData()
        {
            if (_frm != null)
            {
                Application.ShowModelessDialog(_frm);
            }
        }
 
        private static void taskManager_TasksExecutionCompleted(
            object sender, EventArgs e)
        {
            AsyncTaskManager taskManager = sender as AsyncTaskManager;
            if (taskManager != null)
            {
                if (taskManager.ResultData.Count > 0)
                {
                    if (taskManager.ResultData.ContainsKey("Retrieve Google Map Data"))
                    {
                        ShowTaskDataInForm(
                            taskManager.ResultData["Retrieve Google Map Data"]);
                    }
                }
            }
        }
 
        private static void ShowTaskDataInForm(object taskResultData)
        {
            if (_frm != null)
            {
                _frm.Dispose();
            }
 
            _frm = new frmGoogleData(taskResultData);
        }
    }
}

One will notice that a form is initialized if there is result data generated after task execution. For the simplicity, the form is very simple: only a label is place on the form the show the data:

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
 
namespace StartupAsyncTask
{
    public partial class frmGoogleData : Form
    {
        public frmGoogleData()
        {
            InitializeComponent();
        }
 
        public frmGoogleData(object taskData)
        {
            InitializeComponent();
 
            SetData(taskData);
        }
 
        public void SetData(object taskData)
        {
            List<string> data = taskData as List<string>;
            if (data != null)
            {
                StringBuilder str = new StringBuilder();
                foreach (string s in data)
                {
                    str.Append(s + "\n");
                }
 
                lblData.Text = str.ToString();
            }
        }
 
        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Visible = false;
        }
 
        private void frmGoogleData_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            this.Visible = false;
        }
    }
}

In the real world, the form should be designed according to the data generated by the task being executed, and the system tray icon's balloon message may prompt user for viewing task data in some way (maybe keeping the system tray icon for user to double-click to open a data viewing form would be a better option).

Go to this video clip to see the actual action of the code shown here. Pay attention to the lower right corner where Windows system tray is. As you can see, I deliberated setting a longer execution time for that 3 tasks. While the 3 tasks being executed in the background thread, I can keep drawing a polyline in AutoCAD. It worth pointing out, only the Execute() method of the tasks is done in background thread, while the task itself is created/initialized in the same thread as the AutoCAD, so if the task has a very complicated/heavy constructor to initialize and there a few tasks of this kind to be initialized, this initialization would be the normal load on the AutoCAD execution thread.

Extra interest: it may be possible to use Autodesk.AutoCAD.Windows.Pane in AutoCAD's status bar, instead of using Windows system tray icon as user prompting method.

Blog Archive

Labels

3D Modeling 3D Sketch Inventor AI Design AI in Manufacturing AI Tools Architecture Artificial Intelligence AutoCAD AutoCAD advice AutoCAD Basics AutoCAD Beginners AutoCAD Civil3D AutoCAD commands AutoCAD efficiency AutoCAD features AutoCAD File Management AutoCAD Layer AutoCAD learning AutoCAD print settings AutoCAD productivity AutoCAD Teaching AutoCAD Techniques AutoCAD tips AutoCAD training. AutoCAD tricks AutoCAD Tutorial AutoCAD workflow AutoCAD Xref Autodesk Autodesk 2025 Autodesk AI Tools Autodesk AutoCAD Autodesk Fusion 360 Autodesk Inventor Autodesk Inventor Frame Generator Autodesk Inventor iLogic Autodesk Recap Autodesk Revit Autodesk Software Autodesk Video Automation Automation Tutorial Basic Commands Basics Beginner Beginner Tips BIM BIM Implementation Block Editor ByLayer CAD comparison CAD Design CAD File Size Reduction CAD line thickness CAD Optimization CAD Productivity CAD software clean CAD file cleaning command Cloud Collaboration command abbreviations Construction Technology Contraints Create resizable blocks CTB STB Data Reference Data Shortcut design software Design Workflow Digital Design Digital Twin Drafting Standards Drawing Automation Dref Dynamic Block Dynamic Block AutoCAD Dynamic Blocks Dynamic doors Dynamic windows eco design editing commands energy efficiency Engineering Engineering Design Engineering Innovation Engineering Technology engineering tools Excel Express Tools External Reference Fast Structural Design Fusion 360 Generative Design green building Grips heavy CAD file Heavy CAD Files iLogic Industry 4.0 Insight Inventor API Inventor Drawing Template Inventor Frame Generator Inventor Graphics Issues Inventor IDW Inventor Tips Keyboard Shortcuts Learn AutoCAD Machine Learning in CAD maintenance command Management Manufacturing Innovation Metal Structure ObjectARX .NET API Organization OVERKILL OVERKILL AutoCAD Palette PDF Plot Style AutoCAD Practice Drawing Printing Quality professional printing Professional Tips PTC Creo PURGE PURGE AutoCAD ReCap reduce CAD file size Resizable Block Revit Revit Best Practices Revit Workflow Ribbon screen shortcut keys Shortcuts Siemens NX Sketch Small Firms Smart Block Smart Factory SolidWorks Steel Structure Design sustainability Sustainable Manufacturing toolbar Tutorial User Interface (UI) Workbook Workspace XLS Xref