Hi,
I've a C# class which uses a COM component using interop. Here is the sample code:
public class MyClass
{
MyCOMClass myObj=null;
try
{
myObj = new MyCOMClass();
for (int num = 0; num < myArr.Length; num++)
{
//Call a method on myObj and do some processing
}
}
catch(Exception ex)
{
//log exception
}
finally
{
if (myObj != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(myObj);
}
}
}
Here, the for loop runs for about 150 times.
n executing this code, in the catch block, am getting an exception : "COM object that has been separated from its underlying RCW cannot be used."
I tried implementing IDisposable interface and then writing Dispose method:
public class MyClass: IDisposable
{
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(true);
}
protected virtual void Dispose(bool diposeMgdResources)
{
if (!this.disposed)
{
if (diposeMgdResources)
{
if (myObj != null)
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(myObj);
}
}
this.disposed = true;
}
}
}
From the client, I then call dispose on this class like: myClass.Dispose();
But, still am getting the same exception here.What am I missing?
Thanks for reading.