Is it necessary to call Marshal.ReleaseComObject i

2019-07-02 03:25发布

I have VS2010 and added a reference to a COM library to my project and VS embedded a primary interop inside the project.

If I reference objects from the COM library and I want to dispose of them quickly without waiting for the GC, is it needed to call ReleaseComObject ?

标签: com c#-4.0
2条回答
太酷不给撩
2楼-- · 2019-07-02 03:39

There are two types of approaches in terms of cleaning memory.

  • Reference Counting Algorithms
  • Garbage Collection

COM components use reference counting algorithm to reclaim memory. Whenever you do not need a reference of a com component you can call it. But Usually my approach is creating a virtual stack and deleting references like the source code below in C#. .NET guarantees as long as RCW is alive COM components is alive. When RCW is garbage collected release method is invoked. It is not necessary to call release in your code. But it does not effect gc cycles.

void DoSth
{
       {
            RunTimeCallableWrapper area for the code
            ReleaseComObject
       }  
 }
查看更多
萌系小妹纸
3楼-- · 2019-07-02 03:47

Marshal.ReleaseComObject provides a way to immediately drop references to this COM object from everywhere it is being consumed within managed code (because it releases the underlying IUnknown from the RCW that is holding it).

As Hans notes, the generally right course is to simply null your object allow the CLR and GC to do the COM object destruction at the appropriate time.

However, in situations where you need immediate action (COM object holds expensive/scarce resources, or perhaps during shutdown where the sequencing is very complex), calling ReleaseComObject can be the right thing to do.

Martyn

查看更多
登录 后发表回答