Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Releasing COM objects

Tags:

c#

com

I added a reference in a Visual Studio project to some COM library. Now when I create and object in a method, will be this COM object automatically released when program leaves that method? Or should I always release these objects manually? (ReleaseComObject or FinalReleaseComObject?).

like image 982
apocalypse Avatar asked Sep 26 '12 07:09

apocalypse


People also ask

How to release an object in c#?

When you want to free the object, add the following line: obj1 = null; The the garbage collector if free to delete the object (provided there are no other pointer to the object that keeps it alive.)

When to use Marshal ReleaseComObject?

You should use this method to free the underlying COM object that holds references to resources in a timely manner or when objects must be freed in a specific order. Every time a COM interface pointer enters the common language runtime (CLR), it is wrapped in an RCW.


2 Answers

It's certainly not done automatically, and in some cases it can be dangerous to do so (by calling Marshal.ReleaseComObject) as described in this blog post.

For In-Proc COM objects, there's often no need to release COM objects at all.

For Out-Proc COM objects, it can be important to release them, to prevent problems such as Office apps failing to shut down after automation from a .NET client.

In this case, I'd follow the advice in the above linked blog post:

If you are using a COM object in a scoped, single-threaded manner then you can safely call ReleaseComObject on that object when you are done with it.

But if you are using a COM object from multiple places or multiple threads in your application (or from other applications in the same process), you should not call ReleaseComObject

like image 50
Joe Avatar answered Oct 09 '22 06:10

Joe


You can use Marshal.ReleaseComObject: http://msdn.microsoft.com/de-de/library/system.runtime.interopservices.marshal.releasecomobject.aspx

like image 34
Florian Avatar answered Oct 09 '22 05:10

Florian