You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

是否存在计时与事件均在独立线程执行的高分辨率Delphi定时器?

关于高精度线程定时器的解决方案

首先确认你的理解:TJvThreadTimer的计时逻辑确实在独立线程中运行,但OnTimer事件代码会通过消息机制同步到主线程执行,你的理解完全正确。

针对你需要的「独立线程计时+事件代码在该线程执行+分辨率低于10ms」的需求,有以下几种可行方案:

一、自定义线程实现(最灵活,精度可控)

直接基于TThread派生类,用Windows原生的高精度计时函数QueryPerformanceCounter实现循环计时,事件代码直接在线程内执行,无需同步回主线程,分辨率可达到1ms甚至更低。

示例代码:

type
  THighResThreadTimer = class(TThread)
  private
    FInterval: Int64;
    FOnTimer: TNotifyEvent;
    FFreq: Int64;
    procedure SetInterval(const Value: Cardinal);
  protected
    procedure Execute; override;
  public
    constructor Create(CreateSuspended: Boolean);
    // 单位:毫秒,可设置小于10的值
    property Interval: Cardinal write SetInterval;
    // 事件代码直接在当前线程执行
    property OnTimer: TNotifyEvent read FOnTimer write FOnTimer;
  end;

constructor THighResThreadTimer.Create(CreateSuspended: Boolean);
begin
  inherited;
  QueryPerformanceFrequency(FFreq);
  FInterval := 5 * FFreq div 1000; // 默认5ms分辨率
  FreeOnTerminate := False;
end;

procedure THighResThreadTimer.SetInterval(const Value: Cardinal);
begin
  FInterval := Value * FFreq div 1000;
end;

procedure THighResThreadTimer.Execute;
var
  LastTick, CurrentTick: Int64;
begin
  QueryPerformanceCounter(LastTick);
  while not Terminated do
  begin
    QueryPerformanceCounter(CurrentTick);
    if (CurrentTick - LastTick) >= FInterval then
    begin
      if Assigned(FOnTimer) then
        FOnTimer(Self);
      LastTick := CurrentTick;
    end;
    Sleep(1); // 降低CPU占用,若追求极致精度可改为Sleep(0)
  end;
end;

使用时只需创建实例、设置Interval和OnTimer事件,启动线程即可,事件代码完全在独立线程中运行。

二、第三方组件方案

  • OmniThreadLibrary:其中的OTTimer组件是完全基于线程实现的高精度定时器,事件代码直接在组件对应的线程执行,无需同步回主线程,分辨率支持1ms级别,配置简单,适合快速开发。
  • 部分开源/商业组件库(如某些Delphi高性能组件集)提供的线程定时器:核心逻辑和自定义线程类似,封装为可视化组件,支持设计时配置参数。

注意事项

  • 由于事件代码在独立线程执行,若需要操作VCL/FMX控件,必须通过TThread.Synchronize或TThread.Queue同步到主线程,否则会引发访问冲突。
  • 高精度计时会增加CPU占用,可根据实际需求调整Sleep的参数,平衡精度与资源消耗。

内容的提问来源于stack exchange,提问作者Dgbaxter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 17:40:29