TThread和COM - "CoInitialize尚未被调用",尽管在构造函数中调用了CoInitialize

for*_*ajt 8 delphi com multithreading ole tthread

我正在尝试在一个线程中使用COM接口.从我所读到的,我必须CoInitialize/CoUninitialize在每个线程中调用.

虽然这很好用:

procedure TThreadedJob.Execute;
begin
   CoInitialize(nil);

   // some COM stuff

   CoUninitialize;
end;
Run Code Online (Sandbox Code Playgroud)

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

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;
Run Code Online (Sandbox Code Playgroud)

我得到EOleException:CoInitialize没有被称为异常,我不知道为什么.

Dav*_*nan 19

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

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

procedure TThreadedJob.Execute;
begin
  CoInitialize(nil);
  try    
    // some COM stuff
  finally  
    CoUninitialize;
  end;
end;
Run Code Online (Sandbox Code Playgroud)