You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C# Autodesk AutoCAD API的不同代码行之间设置执行延迟

AutoCAD .NET API 多直线绘制添加延迟实现方案

核心注意点

  • 你当前将所有绘图操作封装在同一个事务中,事务提交前所有新增实体不会渲染到AutoCAD界面,因此直接在事务内部添加延迟不会实现逐根显示的效果
  • 不能直接使用Thread.Sleep()直接阻塞线程,会导致AutoCAD主UI线程挂起无响应

实现代码

using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.Runtime;
using System.Threading;

namespace ClassLibrary2
{ 
    public class Class1
    {
        [CommandMethod("DrawLineWithDelay")]
        public static void CreateLineWithDelay()
        {
            Document Mydoc = Application.DocumentManager.MdiActiveDocument;
            Database db = Mydoc.Database;
            Editor edit = Mydoc.Editor;

            // 绘制Line1
            using (Transaction Trans = db.TransactionManager.StartTransaction())
            {
                BlockTable block = Trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                BlockTableRecord btr = Trans.GetObject(block[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

                Point3d p1 = new Point3d(0, 0, 0);
                Point3d p2 = new Point3d(1000, 0, 0);
                Line line_1 = new Line(p1, p2);
                line_1.ColorIndex = 2;
                line_1.SetDatabaseDefaults();
                btr.AppendEntity(line_1);
                Trans.AddNewlyCreatedDBObject(line_1, true);

                Trans.Commit();
            }
            // 刷新界面让Line1即时显示
            Mydoc.UpdateScreen();
            Application.DoEvents();
            // 等待2秒,可自行调整等待时长(单位毫秒)
            Thread.Sleep(2000);

            // 绘制Line2
            using (Transaction Trans = db.TransactionManager.StartTransaction())
            {
                BlockTable block = Trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                BlockTableRecord btr = Trans.GetObject(block[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

                Point3d p3 = new Point3d(1200, 0, 0);
                Point3d p4 = new Point3d(2000, 0, 0);
                Line line_2 = new Line(p3, p4);
                line_2.ColorIndex = 2;
                line_2.SetDatabaseDefaults();
                btr.AppendEntity(line_2);
                Trans.AddNewlyCreatedDBObject(line_2, true);

                Trans.Commit();
            }
            Mydoc.UpdateScreen();
        }
    }
}

关键说明

  • 每绘制一根直线就单独开启并提交事务,确保实体即时写入数据库并渲染到界面
  • 调用Document.UpdateScreen()强制刷新界面,让新增实体立即显示
  • 调用Application.DoEvents()处理AutoCAD消息队列,避免等待过程中界面无响应
  • 如果需要绘制更多直线,重复"单独事务+刷新+延迟"的流程即可

内容的提问来源于stack exchange,提问作者M___KH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 10:09:07