开发者

Getting COM exception when using Interop in a .net app

开发者 https://www.devze.com 2023-01-16 15:30 出处:网络
I\'ve a C# class which uses a COM component using interop. Here is the sample code: public class MyClass

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(t开发者_如何学运维rue); 
            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.


Take a look at this article:

Marshal.ReleaseComObject considered dangerous

You probably don't want to call Marshal.ReleaseComObject().

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号