EaBIM一直以来积极响应国家“十二五”推进建筑业信息化的号召,对建筑领域的信息技术开展深入技术交流和探讨!致力于打造“BIM-建筑师-生态技术”三位一体综合资源交流共享平台,希望为BIM与可持续设计理念及技术的普及做出微小的贡献!!!

萧闫子 发表于 2014-1-8 14:20:05

[用户交互] 让AutoCAD.NET支持后台线程


using System;
using Autodesk.AutoCAD.Runtime;
using System.Windows.Forms;
using Autodesk.AutoCAD.EditorInput;
using acApp = Autodesk.AutoCAD.ApplicationServices.Application;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;

namespace BackgroundProcess
{
public class Commands : IExtensionApplication
{
    static Control syncCtrl;
    public void Initialize()
    {
      // The control created to help with marshaling
      // needs to be created on the main thread
      syncCtrl = new Control();
      syncCtrl.CreateControl();
    }

    public void Terminate()
    {
    }

    void BackgroundProcess()
    {
      // This is to represent the background process
      System.Threading.Thread.Sleep(5000);

      // Now we need to marshall the call to the main thread
      // I don't see how this could ever be false in this context,
      // but I check it anyway
      if (syncCtrl.InvokeRequired)
      syncCtrl.Invoke(
          new FinishedProcessingDelegate(FinishedProcessing));
      else
      FinishedProcessing();
    }

    delegate void FinishedProcessingDelegate();
    void FinishedProcessing()
    {
      // If we want to modify the database, then we need to lock
      // the document since we are in session/application context
      Document doc = acApp.DocumentManager.MdiActiveDocument;
      using (doc.LockDocument())
      {
      using (Transaction tr =
          doc.Database.TransactionManager.StartTransaction())
      {
          BlockTable bt =
            (BlockTable)tr.GetObject(
            doc.Database.BlockTableId, OpenMode.ForRead);

          BlockTableRecord ms = (BlockTableRecord)tr.GetObject(
            bt, OpenMode.ForWrite);

          Line line =
            new Line(new Point3d(0, 0, 0), new Point3d(10, 10, 0));
          ms.AppendEntity(line);
          tr.AddNewlyCreatedDBObject(line, true);

          tr.Commit();
      }
      }

      // Also write a message to the command line
      // Note: using AutoCAD notification bubbles would be
      // a nicer solution
      // TrayItem/TrayItemBubbleWindow
      Editor ed = acApp.DocumentManager.MdiActiveDocument.Editor;
      ed.WriteMessage("Finished the background process!\n");
    }

   
    public void ProcessBackground()
    {
      // Let's say we got some data from the drawing and
      // now we want to process it in a background thread
      System.Threading.Thread thread =
      new System.Threading.Thread(
          new System.Threading.ThreadStart(BackgroundProcess));
      thread.Start();

      Editor ed = acApp.DocumentManager.MdiActiveDocument.Editor;
      ed.WriteMessage(
      "Started background processing. " +
      "You can keep working as usual.\n");
    }
}
}
页: [1]
查看完整版本: [用户交互] 让AutoCAD.NET支持后台线程