2016-12-31 88 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命令并将优先级作为参数传递。 –