Object disposal order in .NET

I got a crazy error yesterday while refactoring my data access layer for a client. I wanted to provide a mechanism to get the output parameters from a stored procedure call. I typically use delegates or events to give the developer the option to get the output parameters if they want them.

So I made a change to the order of events to dispose of the connection earlier (rather than hold onto it longer than necessary--"acquire resources late and release them early," as Microsoft says). My pseudocode looked something like this:

Close and dispose of connection
Call output parameter access callback
Dispose of command object

I was getting back my data, but I started getting an unusual error:

System.Runtime.InteropServices.InvalidComObjectException: COM object that has been separated from its underlying RCW cannot be used.

The error referenced the following:

System.Data.Common.UnsafeNativeMethods.IAccessor.ReleaseAccessor(IntPtr hAccessor, Int32& pcRefCount)

As you might guess, I did not suspect the order of object disposal causing this, so I spent a lot of time looking at other potential issues before nailing this down. I believe there is probably a solution via closing the command's underlying connection rather than destroying it without it realizing. Unfortunately, I have not had time to tinker with this yet.

If you run across this error, try the simple solution. Try closing and disposing of your connection after the command object is closed.

Good luck out there!


Post a Comment