views:

20

answers:

2

Can I know how to deallocate COM server object forcefully from C# .NET if particular condion fails or the object is partially constructed?

The problem is I am using that COM server using DCOM mechanism; in the worst case, when the object is not created fully and I am coming out of application since failure, the COM object is still in memory (showed in COM+ Application component services). If its going beyond some limits, it leads to memory leak and crash. But if its manageable amount of failures, its getting deleted after some point of times.

Sample:- Calculator.App objApp = new Calculator.App();

if( !obj.CanBeUsed() ) { //how to deallocate the COM object objApp }

Note: There is a method GC.Collect() used by Garbase Collector to de-allocate from the heap memory forcefully. Whether I can use this method or .NET franework is giving anyother solution for this particular case?

+1  A: 

Like this:

System.Runtime.InteropServices.Marshal.ReleaseComObject(objApp);
Aamir
There is a MSDN blog saying using ReleaseComObject() is very dangerous. http://blogs.msdn.com/b/visualstudio/archive/2010/03/01/marshal-releasecomobject-considered-dangerous.aspx. You have any points on that?
Snabak Vinod
You talked about releasing the object forcefully, right? Whenever you will do something forcefully, there will be side-effects :)
Aamir
Here side effect shouldn't happen :(. I am going to use for avoiding memory leak only, to help .NET framework :).
Snabak Vinod
+1  A: 

You should try Marshal.FinalReleaseComObject method.

The FinalReleaseComObject method releases the managed reference to a COM object. Calling this method is equivalent to calling the ReleaseComObject method in a loop until it returns 0 (zero).

When the reference count on the COM object becomes 0, the COM object is usually freed, although this depends on the COM object's implementation and is beyond the control of the runtime. However, the RCW can still exist, waiting to be garbage-collected.

The COM object cannot be used after it has been separated from its underlying RCW. If you try to call a method on the RCW after its reference count becomes 0, a InvalidComObjectException will be thrown.

Jakub Šturc
This is a bit dangerous. From MSDN: "Releases all references to a Runtime Callable Wrapper (RCW) by setting its reference count to 0." This means that it will try to forcefully set the reference count to 0 which can be bad because there might be other valid references as well.
Aamir
@Aamir: I thought that the forced deallocation is the point.
Jakub Šturc
There is a MSDN blog saying using ReleaseComObject() is very dangerous. http://blogs.msdn.com/b/visualstudio/archive/2010/03/01/marshal-releasecomobject-considered-dangerous.aspx.
Snabak Vinod