TThread 和 COM - "CoInitialize has not been called",尽管在构造函数中调用了 CoInitialize

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

我正在尝试在线程中使用 COM 接口。根据我的阅读,我必须在每个线程中调用 CoInitialize/CoUninitialize

虽然这工作正常:

procedure TThreadedJob.Execute;
begin
   CoInitialize(nil);

   // some COM stuff

   CoUninitialize;
end;

当我将调用移至构造函数和析构函数时:

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;

我收到 EOleException: CoInitialize has not been called 异常,我不知道为什么。

CoInitialize 为执行线程初始化 COM。 TThread 实例的构造函数在创建 TThread 实例的线程中执行。 Execute 方法中的代码在新线程中执行。

这意味着如果你需要你的TThreadedJob线程初始化COM,那么你必须在Execute方法中调用CoInitialize。或者从 Execute 调用的方法。以下是正确的:

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