Best way to clean COM object in .net application

I am working on an application. Net, which internally uses COM-dll. Of the following 4 ways to free a COM object, which is the best?

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.

+1
source share
2 answers

Either let the GC handle this, as Richard suggested, or your number 2. If you call FinalReleaseComObject, you destroy the shell called by the call, regardless of whether it finds it and other parts of your code. This can seriously confuse other parts of your code. Therefore, you should only call ReleaseComObjectonce per transition to the .NET transition from-COM-COM.

+2
source

5. Let the GC do it.

, COM , .


obj != null, obj null , , .

: , ReleaseComObject FinalReleaseComObject, .

+2

Source: https://habr.com/ru/post/1765075/


All Articles