HanDs
管理员

[Delphi文章] 循环执行的定时器多线程 



{
  2008.02.26 coded by cqwty
  email:cqwty@sina.com
}
unit IntervalThreadUnit;

interface

uses
  Classes, mmsystem, Windows, sysutils, Forms, FileCtrl;

type
  TIntervalThread = class(TThread)
  private
    { Private declarations }
    fInterval: Integer;
    timerid:integer;
    htimerevent:Thandle;
    procedure SetInterval(Value: Integer);
  protected
    procedure Execute; override;
  public
    constructor create;
    procedure SetOver;
  published
    property Interval:Integer read fInterval write SetInterval;
  end;

implementation

constructor TIntervalThread.Create;
begin
  FreeOnTerminate := true;
  Inherited Create(true);
end;

procedure TIntervalThread.SetOver;
begin
  timerid := timesetevent(5,0,TFNTimecallback(htimerevent),0,time_periodic or time_callback_event_set);
end;

procedure TIntervalThread.SetInterval(Value: Integer);
begin
  if Interval <> Value then
    fInterval := Value;
end;

procedure TIntervalThread.Execute;
begin
  htimerevent := CreateEvent(nil, False, False, nil);
  timerid := timesetevent(FInterval*1000,0,TFNTimecallback(htimerevent),0,time_periodic or time_callback_event_set);
  repeat
    if WaitForSingleObject(htimerevent,INFINITE) = WAIT_OBJECT_0 then
    begin
      if Terminated then break;
      DoSomething;
    end;
  until false;
  timekillevent(timerid);
  CloseHandle(htimerevent);
end;

end.

调用的时候需要先创建,然后对该线程的属性赋值,最后在resume即可了。
要结束线程的时候,先调用setover,然后在调用线程自身的terminate即可。
保证了能最快的速度结束正在定时循环执行的多线程。


学习中请遵守法律法规,本网站内容均来自于互联网,本网站不负担法律责任
循环 执行 定时器 线程
#1楼
发帖时间:2016-7-9   |   查看数:0   |   回复数:0
游客组
快速回复