Delphi:TTask 仅在第一次时显得很慢

标签 delphi

单击按钮后,我创建 3 个任务,每个任务都有空过程,并将方法调用和任务列表完成的时间差写入控制台:

procedure TWinTest.BtnThreadTestClick(Sender: TObject);
var
  aTasks: array of ITask;
  aStart: Cardinal;
begin
  aStart := GetTickCount;

  Setlength(aTasks, 3);

  aTasks[0] := TTask.Create(procedure() begin

  end);
  aTasks[0].Start;

  aTasks[1] := TTask.Create(procedure() begin

  end);
  aTasks[1].Start;

  aTasks[2] := TTask.Create(procedure() begin

  end);
  aTasks[2].Start;

  TTask.WaitForAll(aTasks);


  Writeln( GetTickCount - aStart, 'ms');
end;

第一次调用需要 31 毫秒,后续调用需要 0 毫秒。

enter image description here

为什么第一次调用比后续调用慢?也许delphi缓存线程并在后续调用中重用它?

最佳答案

是的,任务线程默认被缓存(在线程池中)。这是有记录的行为:

Tutorial: Using Tasks from the Parallel Programming Library

This tutorial shows how to implement an application using tasks from the Parallel Programming Library (PPL). Tasks are units of work that are in a queue and start when the CPU time is available. Tasks can run operations in parallel. There is a master thread that manages this queue and allocates threads from the thread-pool to do work of the tasks. This thread-pool has a number of threads that depends on the number of CPUs that are available.

您可以通过创建 TThreadPool 来自定义池的行为。对象并将其传递给 TTask构造函数:

If desired, Create can also be given a parameter of TThreadPool from which the instance of TTask may draw the thread resources it needs. Without specifying an instance of TThreadPool, resources are drawn from a default based upon the CPU and threading capabilities of the platform.

关于Delphi:TTask 仅在第一次时显得很慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56891154/

相关文章:

delphi - 接口(interface)的多重继承

应用程序需要 Delphi 5 来实现自定义插件——较新的 Delphi 版本是否向后兼容?

delphi - 如何在Delphi StringGrid单元格中移动光标位置?

delphi - 为什么当我使用 "message"指令时,我的控件中收不到消息?

delphi - 我可以嵌套关键部分吗? TCriticalSection 可以嵌套吗?

delphi - 在运行时创建组件 - Delphi

html - 如何在 Delphi 2007 中将文件下载到受密码保护的位置

德尔福 FireDAC : how to refresh data in cache

delphi - 在 Delphi XE2 上安装 DWScript 时必须重新编译“designide”

delphi - 在 Delphi 中将 TMyQuery 数据集转换为 TClientDataSet