2016-08-15 29 views
8

我想在線程中使用COM接口。從我讀過的內容來看,我必須在每個線程中調用CoInitialize/CoUninitializeTThread和COM - 「CoInitialize尚未被調用」,雖然CoInitialize在構造函數中調用

雖然這是工作的罰款:

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的沒有被調用例外,我沒有線索爲什麼。

回答

18

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

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

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

謝謝你閃電般的快速回答。 – forsajt