.Net Error:- “COM object that has been separated from its underlying RCW cannot be used”

Background

Last night after a long day of code rewrite, ran into an error that threatened to force me to discard the numerous optimizations I had taken the time and effort to labor over.

 

Error Message

Here is the full error message:-


Exception Type:- System.Runtime.InteropServices.InvalidComObjectException

Exception Source:- mscorlib

Exception Message:- COM object that has been separated from its underlying RCW cannot be used.

Stack Trace:- at System.StubHelpers.StubHelpers.GetCOMIPFromRCW(Object objSrc, IntPtr pCPCMD, IntPtr& ppTarget, Boolean& pfNeedsRelease)
at System.Data.Common.UnsafeNativeMethods.IAccessor.ReleaseAccessor(IntPtr hAccessor, Int32& pcRefCount)
at System.Data.OleDb.RowBinding.Dispose()
at System.Data.OleDb.OleDbCommand.InitializeCommand(CommandBehavior behavior, Boolean throwifnotsupported)
at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult)
at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
at System.Data.OleDb.OleDbCommand.ExecuteReader(CommandBehavior behavior)
at worker.process1()

Remediation

Outline

  1. Code Review
  2. Code Rewrite

Code Review

Please review your code.

That is:-

  1. Opened Connections
    • Ask yourself do you have connections that could be opened
    • Unclosed connections can get in the way of the runtime marking the object for deallocation
  2. Dangling Pointers / Handles
    • Could and do you have dangling pointers/handles

Code Rewrite

Here is a very rough draft of the original code:-

Code

Original

 


class1 obj1 = new class1();

int iValueMax = 10;
int iValue = 0;

while (iValue < iValueMax)
{

  iValue = iValue +1;

  obj1.method1();

}

obj1 = null;

 
 

Revision


int iValueMax = 10;
int iValue = 0;

while (iValue < iValueMax)
{
   class1 obj1 = new class1();

   iValue = iValue +1;

   obj1.method1();

   obj1 = null;

}

Explanation

Yes, Microsoft .Net does a very job of object lifetime management.

Yet, one can still run into race and contention issues where objects are not completely deallocated, cleaned, and freed up; before they are used again, especially in a loop.

So please help yourself and the compiler via implicit means ( “using”  keyword ).

Or more explicitly, instantiate and deallocate each “troubled” object inside the loop.

Summary

Unfortunately sacrificing conservative resource allocation for saneness.

 

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s