Search code examples
c#listcomobject

Does clearing a List containing ComObject, release all of them in c#?


I have a list containing different ComObjects. If I do myList.Clear() would it be enough or should I loop through it and does this.

for (int i = 0; i < myList.Count; ++i)
     if (System.Runtime.InteropServices.Marshal.IsComObject(myList[i]))
         System.Runtime.InteropServices.Marshal.ReleaseComObject(myList[i]);

     myList.Clear();

Solution

  • It's not broken, so don't fix it. If you are not having a problem with the collection semantics of a COM object, let the garbage collector do its work. If you are having a problem, then carefully describe the problem and what you understand about COM interop in C#.

    In particular, calling ReleaseComObject to manage the RCW or worse, Release on the actual pUnknown is a for interop experts only sharp tool. Incorrect use of these tools can get you into any number of horrible situations full of crashes and memory corruptions. (If you ever see a "COM object is detached from its RCW" exception, you know someone who thought they knew what they were doing called ReleaseComObject wrong.)

    If you don't understand what an RCW is or what it is for or how it differs from the underlying COM object, stop writing interop code until you do understand it. The memory safety system is designed for your safety and convenience; don't mess with it unless you can describe all of the consequences of doing so.

    I note that your actual question was never answered:

    Does clearing a List containing ComObject, release all of them in c#?

    Of course not. Why should it? It clears the list. Clear the list when your program logic requires the list to be cleared. Don't clear a list because you believe that doing so has some knock-on effect on other code!