【问题标题】:How to set a higher task priority to a Parallel.Async background task?如何为 Parallel.Async 后台任务设置更高的任务优先级?
【发布时间】:2017-05-15 09:08:58
【问题描述】:

我需要为Parallel.Async 后台任务分配更高的任务优先级。由于 OmniThreadLibrary 有 SetPriority:如何为这个 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;

【问题讨论】:

    标签: delphi delphi-10.1-berlin omnithreadlibrary


    【解决方案1】:

    替换

    Parallel.TaskConfig.OnTerminated(...
    

    例如

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

    优先级的可能值是

    tpIdle, tpLowest, tpBelowNormal, tpNormal, tpAboveNormal, tpHighest
    

    请注意,这只会影响进程中线程的优先级,不会赋予进程本身更高的优先级。有关详细信息,请参阅 SetThreadPriority 函数的文档。

    【讨论】:

    • 非常感谢你,奥拉夫。但是,当使用tpHighest 时,必须指定正确的命名空间:Parallel.TaskConfig.SetPriority(TOTLThreadPriority.tpHighest).OnTerminated(...。那是因为 TThreadPriority 类进来了:E2010 Incompatible types: 'TOTLThreadPriority' and 'TThreadPriority'
    • 这是否意味着Parallel.Async 部分中的代码使用tpHighest 比使用tpNormal 执行得更快?
    • 如果我正确理解了文档,Parallel.Async 部分中的代码将比此过程中的其他线程获得更多的 CPU 时间。如果其他线程什么都不做,我不确定是否会有明显的效果。要更改整个进程的优先级,可以通过 API 调用 (How to set the process priority in C++) 或使用 Windows 任务管理器中的“更改优先级”菜单或使用“开始”命令行命令启动程序并将优先级作为参数。
    • @user1580348 您似乎陷入了对多线程开发的常见误解的陷阱。重要的是要理解:线程不会让代码运行得更快——永远!它们只会让代码可能同时运行。如果您正在做多件事,您将能够并行执行它们。每个任务仍将需要相同数量的处理时间和资源。增加一个线程的优先级意味着它可能(如果没有被其他东西阻塞)在许多线程竞争 CPU 时获得更多的处理器时间。 这是最好的希望
    猜你喜欢
    • 1970-01-01
    • 2014-10-29
    • 2015-07-20
    • 1970-01-01
    • 2016-08-11
    • 2012-01-04
    • 2012-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多