This VB.net function I use over and over to create a generally fool proof (as if there is such a thing) method of structuring a transaction based routine.
I have db, thisdrawing, and ed defined as public variables that i resuse like mad, wouldn't necessarily recommend that approach.
'Using' just helps with stronger garbage collection, but it can be troublesome at times, because objects defined inside dissapear when you end using.
I also inclosed a basic error trapping try/catch block that throws the error up when found (this stops the rest of the routine between try and catch from processing, so you may want to handle your errors in different ways and at different places)
You can nest transactions a lot (like 256 i think) before AutoCAD will die. JUST BE SURE TO DISPOSE EACH ONE...
Everytime you enter the line trans.commit() will fire off autocad events, so if your listening you may need to ignore the events during processing. (if ignore = true then exit sub)
Document locking helps keep your palettes/forms and autocad application playing nicely.
All these lines I tend to write over and over by force when debugging my code. When I skip them for convenience, AutoCAD is sure to tell me about it.
Public Function EmptyFunction() As ObjectId
Dim dlock As DocumentLock = Nothing
Dim oid As ObjectId = Nothing
Using trans As Transaction = _ db.TransactionManager.StartTransaction
Try
dlock = ThisDrawing.LockDocument
'do something to generate an objectid for the
'function to return
trans.Commit()
Catch ex As System.Exception
Dim aex As New System.Exception("Error finding or creating a new " & "" & " EmptyFunction. ", ex)
Throw aex
Finally
If Not trans Is Nothing Then trans.Dispose()
If Not dlock Is Nothing Then dlock.Dispose()
End Try
End Using
Return oid
End Function