Freeing unused libraries while using COM!
It’s a good practice to free unused COM dlls if it’s not used anymore. So is there a function call which does this?
Yes, it’s called CoFreeUnusedLibraries or CoFreeUnusedLibrariesEx!
Are the libraries immediately removed from the internal COM dll list, no there is a time delay of 10 minutes for MTAs and neutral apartment models, this is to avoid multi threaded race conditions but there is no delay for STAs.
To avoid a ten minute delay call CoFreeUnusedLibrariesEx with the delay parameter set to some reasonable value, but avoid values of zero allowing a dll to do cleanup stuff. MSDN says there will be problems if delay is set to zero.
Internally COM maintains a list of COM dlls loaded for a process, and when CoFreeUnusedLibraries is called this dll is moved to “candidate-for-removal” list as per MSDN. So just in case if the dll get’s used again while in this list, it’s moved back to the active list of COM libraries of loaded for a process.
CoFreeUnusedLibrariesEx/CoFreeUnusedLibraries calls DllCanUnloadNow to figure out whether a COM dll is ready to be unloaded, if it’s ready then it returns S_OK else S_FALSE.