I have written a multi thread unmanaged application which uses COM objects in its worker threads. Everything went fine until I started using .NET objects exported as COM to do the work.
Playing around with the code and commenting out parts of the .NET object functionality I managed to pin it down to the usage of COM objects from within the .NET objects. To summarize:
- My program starts a couple of worker threads.
- Each worker thread initializes a .NET based COM object to do the work.
- The .NET based COM objects use unmanaged COM objects internally.
To my surprise the memory consumption of the application started climbing up steadily until OutOfMemory exception started to appear.
Here is my .NET implementation:
void DoSomeWork()
{
IComObject O = new ComObjectClass();
try
{
// do something
}
finally
{
Marshal.ReleaseComObject(O);
}
}
If I comment out this function, the memory leaks disappear. If I call GC.Collect() in it the memory leak still happens.
Any ideas as to what may be going on?
EDIT: Some more info based on comments and answers:
- All threads created are running in the MTA.
- All COM objects implement IMarshal and use the Free Threaded Marshaler.
- It doesn't matter what do something is - even a int i=0;i++; generates the leak.
- The object noted by ComObjetClass is old and tested. This doesn't mean it's not faulty but is not something glaring.
- I tried repeatedly creating the COM object from a C# program, both on the main thread and with another created thread. In both cases the memory leak disappeared. It seems that the cross from unmanaged code to managed and the back again is essential. Removing any part of it results in the problem disappearing.