AutoCAD .NET二次开发(三)

在ArcGIS中,锁是一个经常遇到的东西,在打开一个该当时要锁定,编辑一个文档是再次锁定。要深入理解这个,要学习一下进程与线程。在CAD.NET中,也有Lock与Unlock。

获取一个文档,在进行处理前应当LockDocument,像官网帮助所说,因为修改或访问CAD的请求随时随地都在发生,为避免与其他请求冲突,我们有责任在修改前锁定文档。但是,某些情形下的锁定文档会导致在更新数据库过程中锁定犯规。

AutoCAD .NET二次开发(三)

下列四种情况我们需要锁定:

(1)从无模式对话框与CAD交互时;

(2)访问已调入的文档不是当前文档时;

(3)应用程序作为COM服务器时;

(4)用会话命令标志注册命令时。

例如,向非当前文档的模型或图纸空间添加实体时,就需要锁定文档。我们使用要锁定的数据库对象的LockDocument方法,调用LockDocument方法时,返回一个DocumentLock对象。

一旦修改完已锁定数据库,就要将数据库解锁。解锁数据库,我们调用DocumentLock对象的Dispose方法。我们还可以使用Using语句,Using语句运行结束,数据库也就解锁了。也许,这四种情况我目前并不是很理解,但在以后的学习中,应该用得着。

而我总喜欢看看违背它的意愿来尝试一次,我去掉了锁定代码,结果调试报错:eLockViolation

AutoCAD .NET二次开发(三)

下是是官网帮助的例子:本例新建一个文档然后绘制一个圆。文档创建后,新文档的数据库被锁定,然后圆添加到文档,添加完圆后数据库解锁,相应文档窗口置为当前。

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

 [CommandMethod("LockDoc", CommandFlags.Session)]
public static void LockDoc()

{

  // Create a new drawing新建图形

  DocumentCollection acDocMgr = Application.DocumentManager;

  Document acNewDoc = acDocMgr.Add("acad.dwt");

  Database acDbNewDoc = acNewDoc.Database;

   // Lock the new document锁定新文档

  using (DocumentLock acLckDoc = acNewDoc.LockDocument())

  {

      // Start a transaction in the new database启动新数据库事务

      using (Transaction acTrans = acDbNewDoc.TransactionManager.StartTransaction())

      {

          // Open the Block table for read打开并读块表,

          BlockTable acBlkTbl;

          acBlkTbl = acTrans.GetObject(acDbNewDoc.BlockTableId, OpenMode.ForRead) as BlockTable;

           // Open the Block table record Model space for write

          //打开并写模型空间的块表记录

          BlockTableRecord acBlkTblRec;

          acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace],

                                          OpenMode.ForWrite) as BlockTableRecord;

           // Create a circle with a radius of 3 at 5,5

          //以半径3圆心(5,5)绘圆

          Circle acCirc = new Circle();

          acCirc.Center = new Point3d(5, 5, 0);

          acCirc.Radius = 3;

           // Add the new object to Model space and the transaction

          //向模型空间和事务添加新对象

          acBlkTblRec.AppendEntity(acCirc);

          acTrans.AddNewlyCreatedDBObject(acCirc, true);

           // Save the new object to the database提交事务,保存新对象到数据库

          acTrans.Commit();

      }

       // Unlock the document解锁文档using语句到此结束

  }

   // Set the new document current将新文档置为当前

  acDocMgr.MdiActiveDocument = acNewDoc;

}

  

参考:http://www.360doc.com/content/12/0909/12/8463843_235156523.shtml

        http://www.cadkong.com/doc/3732