How to work with COM objects from managed code in C #?

Here, for example, I perform some interop access operations, but after I have finished working with Access, it continues to hang in processes until I close the program itself.

What am I doing wrong?

I tried to force garbage collection, but it did not help.

3 answers 3

It is necessary to release all references to RCW :

Marshal.FinalReleaseComObject(comObject); 

or

 while (Marshal.ReleaseComObject(comObject) > 0){} 

    At the COM object, you need to call a method to release the resources.

    Like that:

     if (application != null) { application.WorkbookBeforeClose -= new Excel.AppEvents_WorkbookBeforeCloseEventHandler(application_WorkbookBeforeClose); application.Quit(); Marshal.ReleaseComObject(application); GC.Collect(); GC.WaitForPendingFinalizers(); process.WaitForExit(100); } 
    • If I process a collection of objects in foreach, should I free up memory at the end of the iteration? - iluxa1810
    • Show the loop code. - Mstislav Pavlov
    • @ iluxa1810 most likely you just do not call .Quit() or .Quit(0) . From the application, you must explicitly exit the code. - PashaPash
    • And if I work with a collection of COM objects through for each, do I have to release them at the end of the loop through ReleaseComObject? Suppose I am processing a collection of requests from Access. - iluxa1810

    Do not use the GC.Collect() method, implement the destructor to free up memory, and do not free up memory / delete objects in foreach

    Update

     class YourClass { ~YourClass() // destructor { /* лучше всего использовать unmanaged код для освобождения памяти из под COM обьектов , в стиле C/C++ */ } } 
    • How do destructors that free memory look in C #? - PashaPash
    • one
      ~ YourClass () does not free memory allocated for this class. and to release unmanaged resources, you need to use not the destructors, but the dispose / finalize pattern. - PashaPash
    • those. in general there are cases when it is really a shortage of the finalizer, but when working with PIA there is usually just not enough explicit exit from the application: ( - PashaPash