RCW & reference counting when using COM interop in C#

后端 未结 5 2051
孤独总比滥情好
孤独总比滥情好 2020-12-04 15:46

I have an application that uses Office interop assemblies. I am aware about the \"Runtime Callable Wrapper (RCW)\" managed by the runtime. But I am not very sure how the ref

5条回答
  •  温柔的废话
    2020-12-04 16:50

    You shouldn't need any special treatment. The runtime only keeps one reference to the COM object. The reason for this is that the GC tracks all managed references, so when the RCW goes out of scope and is collected, the COM reference is released. When you pass around a managed reference, the GC is tracking it for you - this is one of the biggest advantages of a GC-based runtime over the old AddRef/Release scheme.

    You don't need to manually call Marshal.ReleaseComObject unless you want more deterministic release.

提交回复
热议问题