Best way to clean up a COM object in a .net applic

2019-08-03 03:53发布

Am working on a .Net windows application which internally uses a COM dll. Out of the following 4 ways of releasing a COM object, which is the best one?

1.
 if (obj != null)
                {
                    Marshal.ReleaseComObject(obj);
                }

2.
 if (obj != null)
                {
                    Marshal.ReleaseComObject(obj);
                    obj=null;
                }


3.if (obj != null)
                {
                    Marshal.FinalReleaseComObject(obj);
                }


4.if (obj != null)
                {
                    Marshal.FinalReleaseComObject(obj);
                    obj=null;
                }

Thanks for reading.

标签: com interop
2条回答
你好瞎i
2楼-- · 2019-08-03 04:06

5. Let the GC do it.

Which is fine unless the COM component is holding on to significant resources you need.


If you are basing your approach on checking obj != null then setting obj to null is a good idea, unless you are sure this code will not be called multiple times.

The best way: need more details about the implementation of your application to give specific advise between use of ReleaseComObject and FinalReleaseComObject, but ideally the answer would be neither.

查看更多
▲ chillily
3楼-- · 2019-08-03 04:28

Either just let the GC deal with it as Richard suggested, or your number 2. If you call FinalReleaseComObject, you will destroy the runtime callable wrapper, regardless if it's found its way to other parts of your code as well. This could seriously confuse other parts of your code. So you should only call ReleaseComObject once per crossing-into-.NET-land-from-COM transition.

查看更多
登录 后发表回答