2016-12-31 84 views
1

我需要爲Parallel.Async後臺任務分配更高的任務優先級。由於OmniThreadLibrary有SetPriority:我如何設置此Parallel.Async任務的特定優先級?如何將更高的任務優先級設置爲Parallel.Async後臺任務?

uses 
    CodeSiteLogging, 
    OtlParallel, OtlTaskControl, OtlTask; 

procedure TForm2.btnParallelAsyncClick(Sender: TObject); 
begin 
    CodeSite.Send('btnParallelAsyncClick 1'); 

    Parallel.Async(
    procedure(const task: IOmniTask) 
    var 
     a: Integer; 
    begin 
     // executed in background thread: 
     a := 1 + 1; 
     Sleep(2000); 
     CodeSite.Send('Executed in Async Thread', a); 

     task.Invoke(// used to execute code in main thread 
     procedure 
     begin 
      CodeSite.Send('task.Invoke executed in main thread', a); 
     end); 

     Sleep(2000); 
     CodeSite.Send('Again executed in Async Thread', a); 
    end, 
    Parallel.TaskConfig.OnTerminated(
    procedure(const task: IOmniTaskControl) 
    begin 
     // executed in main thread: 
     CodeSite.Send('After background thread termination: Executed in Main Thread'); 
    end 
    ) 
    ); 

    CodeSite.Send('btnParallelAsyncClick 2'); 
end; 

回答

1

更換

Parallel.TaskConfig.OnTerminated(... 

與例如

Parallel.TaskConfig.SetPriority(tpAboveNormal).OnTerminated(... 

可能值的優先級是

tpIdle, tpLowest, tpBelowNormal, tpNormal, tpAboveNormal, tpHighest 

請注意,這隻會影響給予優先線程內你的過程並沒有給過程本身更高的優先權。有關更多信息,請參閱SetThreadPriority函數的文檔。

+0

非常感謝,奧拉夫。但是,當使用'tpHighest'時,必須指定正確的名稱空間:'Parallel.TaskConfig.SetPriority(TOTLThreadPriority.tpHighest).OnTerminated(...'。這是因爲TThreadPriority類出現了:'E2010 Incompatible types:' TOTLThreadPriority'和'TThreadPriority'。 – user1580348

+0

這是否意味着'Parallel.Async'部分中的代碼將會比'tpNormal'更快地執行?' – user1580348

+0

如果我正確理解文檔中的'Parallel .Async'部分會比此進程中的其他線程獲得更多的CPU時間,如果其他線程什麼都不做,我不確定是否會有明顯的效果。要改變整個進程的優先級,可以通過API調用來實現([如何在C++中設置進程優先級](http://stackoverflow.com/questions/5216347/how-to-set-the-process-priority-in-c))或使用「更改優先級」菜單Windows任務管理器或使用「開始」命令li啓動程序ne命令並將優先級作爲參數傳遞。 –

相關問題