TThread and COM - "CoInitialize was not called," although CoInitialize is called in the constructor

I am trying to use a COM interface in a stream. From what I read, I should call CoInitialize/CoUninitialize in each thread.

While this works fine:

 procedure TThreadedJob.Execute; begin CoInitialize(nil); // some COM stuff CoUninitialize; end; 

when I go to constructor and destructor:

 TThreadedJob = class(TThread) ... protected procedure Execute; override; public constructor Create; destructor Destroy; override; ... constructor TThreadedJob.Create; begin inherited Create(True); CoInitialize(nil); end; destructor TThreadedJob.Destroy; begin CoUninitialize; inherited; end; procedure TThreadedJob.Execute; begin // some COM stuff end; 

I get an EOleException: CoInitialize was not caused by an exception, and I don't know why.

+8
multithreading delphi com ole
source share
1 answer

CoInitialize initializes COM for the executable thread. The container of the TThread instance TThread executed in the thread that creates the TThread instance. The code in the Execute method executes in a new thread.

This means that if you need a TThreadedJob stream to initialize the COM code, you must call CoInitialize in the Execute method. Or a method called from Execute . Correctly:

 procedure TThreadedJob.Execute; begin CoInitialize(nil); try // some COM stuff finally CoUninitialize; end; end; 
+18
source share

All Articles