Mixed C++ / C# application leaking memory

I had one customer have an issue with a mixed language application leaking large amounts of memory over time. I noticed that the finalizer queue for .NET keeps growing. With WinDbg I was able to diagnose that the stack trace of the finalizer queue was stuck on a WaitForSingleObject followed by some COM functions. The funny thing is that the customer was not using any COM directly, but underneath the hood there was some .NET object that was using COM.

Since the threads in this application were spawned with the unmanaged CreateThread, COM was not being initialized properly and therefore not defaulting to an MTA state. There were two ways in my mind to fix this problem:


  1. Initialize COM in each thread as STA and have an event loop during idle times on each thread.
  2. Or Initialize COM in each thread as MTA (due to this process not involving any UI, MTA was acceptable).
All of a sudden, on the next launch with the MTA CoInitialize at the beginning of each thread, the memory issues went away as the finalizer was no longer blocked waiting for a message pump to process destruction of the COM objects. Problem solved!

Comments

Post a Comment

Popular posts from this blog

Gain SSH access to the Buffalo LinkStation 421e

Enable Buffalo LinkStation 421e SFTP

PublicKey attribute in .NET Framework 3.5 SP1 Does not match that of file...