【发布时间】:2016-07-06 10:10:52
【问题描述】:
我正在编写一个 AutoCAD 插件。我正在使用事务来获取一些对象,但我提出了一个问题 - 我是否需要关闭(处置)通过事务接收的对象?
文档中写到,当调用 Commit() 方法时,事务会关闭通过事务接收到的每个对象。
void Commit() -- 该函数提交在 Transaction 期间打开的所有 DBObjects 中所做的更改,然后关闭它们。
但是当我不调用这个方法时会发生什么?例如,我只使用事务来打开一个对象并接收其层名称。类似于以下内容:
Database hostapp_workdb = HostApplicationServices.WorkingDatabase;
using ( Application.DocumentManager.MdiActiveDocument.LockDocument() )
using ( Transaction transaction = hostapp_workdb.TransactionManager.StartTransaction() )
{
Entity entity = transaction.GetObject(objectId, OpenMode.ForRead) as Entity;
if ( entity != null )
layer = entity.Layer;
}
如你所见,这里我没有调用 Commit()。在这种情况下会发生什么?实体是否会关闭(因为事务在使用它必须被处置,所以我想它必须关闭所有对象。但我在文档中没有找到任何确认,所以这只是我的假设)。
也许我需要这样做:
ObjectId objectId = new ObjectId();
string layer = string.Empty;
Database hostapp_workdb = HostApplicationServices.WorkingDatabase;
using ( Application.DocumentManager.MdiActiveDocument.LockDocument() )
using ( Transaction transaction = hostapp_workdb.TransactionManager.StartTransaction() )
{
using ( Entity entity = transaction.GetObject(objectId, OpenMode.ForRead) as Entity )
{
if ( entity != null )
layer = entity.Layer;
}
}
鼓励链接到官方来源。
谢谢。
【问题讨论】:
-
通常您不需要处置每个实体。在第二种情况下,如果 'entity' 为 'null',则在调用 'entity.Dispose' 时会得到 'Exception'。
-
@SarveshMishra 不,我不会。我已经运行了该代码,即使实体为空 - 我也不会遇到任何异常。