簡體   English   中英

TThread和COM-“未調用CoInitialize”,盡管在構造函數中已調用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沒有被稱為異常,我也不知道為什么。

CoInitialize初始化執行線程的COM。 TThread實例的構造TThread在創建TThread實例的線程中執行。 Execute方法中的代碼在新線程中執行。

這意味着如果您需要TThreadedJob線程進行COM初始化,則必須在Execute方法中調用CoInitialize 或從Execute調用的方法。 以下是正確的:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM