CAD—定义委托异步添加实体

   先简单的介绍下同步和异步委托:

        (1)同步委托:委托的Invoke方法用来进行同步调用。同步调用也可以叫阻塞调用,它将阻塞当前线程,然后执行调用,调用完毕后再继续向下进行。

        (2)异步委托:异步调用不阻塞主线程,而是把调用在线程池中的新线程中执行,我们可以不必关心,也无需关心这个“新线程”是怎么定义的
   委托的异步调用通过BeginInvoke和EndInvoke来实现。
        直接上代码看的直观.   

代码
 1         public delegate void AddCircleHandler(Point3d center,double radius);//定义委托
 2         Document doc = AsApp.DocumentManager.MdiActiveDocument;
 3         Editor ed = AsApp.DocumentManager.MdiActiveDocument.Editor;
 4         Database db = AsApp.DocumentManager.MdiActiveDocument.Database;
 5         [CommandMethod("AddCircle")]
 6         public void AddCircle()
 7         {
 8             //定义
 9             Point3d center = Point3d.Origin;
10             AddCircleHandler circle = new AddCircleHandler(AddCircle);
11 
12             //操作
13             Transaction tr = db.TransactionManager.StartTransaction();
14             using (tr)
15             {
16                 PromptPointOptions opt = new PromptPointOptions("选择圆的中点");
17                 PromptPointResult res = ed.GetPoint(opt);
18                 if (PromptStatus.OK != res.Status)
19                 {
20                     return;
21                 }
22                 center = res.Value;
23 
24                 //Commit
25                 tr.Commit();
26             }
27 
28             ed.WriteMessage("\n异步调用前");
29             IAsyncResult myResult =  circle.BeginInvoke(center, 300nullnull);//异步添加圆
30 
31             while (!myResult.IsCompleted)
32             {
33                 ed.WriteMessage("\n异步添加圆正在执行。。。。!");
34             }
35             ed.WriteMessage("\n异步调用后");
36         }
37         
38         /// <summary>
39         /// 添加实体
40         /// </summary>        
41         private void AddCircle(Point3d center, double radius)
42         {
43             //操作
44             Transaction tr = db.TransactionManager.StartTransaction();
45             using (tr)
46             {
47                 BlockTable bt = tr.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
48                 BlockTableRecord btr = tr.GetObject(db.CurrentSpaceId, OpenMode.ForRead) as BlockTableRecord;
49 
50                 //Add Circle
51                 using (DocumentLock docLock = doc.LockDocument())
52                 {
53                     Circle circle = new Circle(center, new Vector3d(001), radius);
54                     btr.UpgradeOpen();
55                     btr.AppendEntity(circle);
56                     tr.AddNewlyCreatedDBObject(circle, true);
57 
58                     //Commit
59                     tr.Commit();
60                 }
61             }
62         }
原文地址:https://www.cnblogs.com/wangyong/p/1680663.html