Search code examples
delphidelphi-10.1-berlinomnithreadlibrary

How to set a higher task priority to a Parallel.Async background task?


I need to assign a higher task priority to a Parallel.Async background task. Since the OmniThreadLibrary has SetPriority: How can I set a specific priority to this Parallel.Async task?

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;

Solution

  • Replace

    Parallel.TaskConfig.OnTerminated(...
    

    with for example

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

    Possible values for the priority are

    tpIdle, tpLowest, tpBelowNormal, tpNormal, tpAboveNormal, tpHighest
    

    Please be aware that this only affects the priority given to the threads within your process and does not give the process itself a higher priority. See the documentation for the SetThreadPriority function for more info.