![](/img/trans.png)
[英]COM object methods are not executed on the thread that CoInitialize-d and created the object
[英]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.