Click to See Complete Forum and Search --> : COM problems and Multithreading


KevinTT
April 14th, 2010, 08:26 AM
Unfortunately, I spend most of my time with Linux so I am not all that familiar with COM, but I have been thrown into a project where I have to use COM to communicate with a database.

So, in this application I create threads for Readers and Writers of the database. In the Reader and Writer thread loop method I call CoInitializeEx before I enter the loop and CoUinitialize when I exit the loop. The Reader class works just find, I can create and destroy connections at will. However, I can only create/destroy the writer connection exactly 3 times before I receive a class not found error. After some testing I discovered, that if I call the CoInitializeEx in some other thread(along with the writer thread), it fixes my problem with the Writer thread. It does not matter if it called where the GUI is created or by simply opening a Reader connection, as long as another CoInitializeEx has been called I can open and close Writer connections.

I am not too familiar with COM but it is my understanding that the CoInitialize call only affects the thread in which it was called, so there is no reason that the COM in a Reader thread should fix the COM in a Writer thread. Can someone shed some light on this issue?

MrViggy
April 14th, 2010, 10:31 AM
Actually, CoInitializeEx (http://msdn.microsoft.com/en-us/library/ms695279%28VS.85%29.aspx) must be called at least once (typically only once) for every thread that will be using COM functionality. You must be calling it in the Writer thread, somewhere.

Viggy

KevinTT
April 14th, 2010, 12:06 PM
That is correct. Sorry if I was unclear in the original post. I am calling CoInitializeEx in the Writer thread. To make it work correctly, I need another active CoInitializeEx call in a different thread. If I launch a Reader thread before the Writer thread everything works correctly until CoUnInitialize is called in the Reader thread.

Is it possible that this is really an issue with the implementation of the COM object I am using from the imported DLLs?