Depending on the main function of Waitabletimer, it is a bit inappropriate to put it on the topic of "Thread Synchronization", and it's time to end it.
//重新看看那个 APC 回调函数的格式:
procedure TimerAPCProc(
lpArgToCompletionRoutine: Pointer;
dwTimerLowValue, dwTimerHighValue: DWORD
); stdcall;
The last two arguments for Timerapcproc are actually passing a value that you want to combine into a tfiletime type of time when you use it.
This time is the time the APC function is invoked, slightly modifying the example above to see:
Code files:
Unit Unit1
Interface
uses
Windows, Messages, sysutils, variants, Classes, Graphics, Controls, Forms ,
Dialogs, Stdctrls;
Type
TForm1 = Class (Tform)
Button1:tbutton;
Button2:tbutton;
Procedure Button1Click (sender:tobject);
Procedure Button2click (sender:tobject);
Procedure Formdestroy (sender:tobject);
End;
Var
Form1:tform1
Implementation
{$R *.DFM}
var
htimer:thandle;
{APC Function}
Procedure Timerapcproc (lpargtocompletionroutine:pointer; dwtimerlowvalue:dword;
Dwtimerhighvalue:dword); stdcall;
var
utcfiletime,localfiletime:tfiletime;
Systemtime:tsystemtime;
Datetime:tdatetime;
Begin
{The time}
Utcfiletime.dwlowdatetime: = Dwtimerlowv to Dwtimerlowvalue and Dwtimerhighvalue and to a tfiletime format} Alue;
Utcfiletime.dwhighdatetime: = Dwtimerhighvalue;
FileTimeToLocalFileTime (Utcfiletime, localfiletime); {Timed from World standard to local time}
FileTimeToSystemTime (LOcalfiletime, SystemTime); {Go to system format time}
DateTime: = Systemtimetodatetime (SystemTime); {Go to Tdatetime} again
Form1.text: = Datetimetostr (DateTime);
SleepEx (INFINITE, True);
End;
{thread entry function}
function Mythreadfun (p:pointer): Integer; stdcall;
var
duetime:int64;
Begin
Duetime : = 0;
If SetWaitableTimer (Htimer, duetime, 1000, @TimerAPCProc, Nil, False) then
begin
SleepEx (INFINITE, True);
End;
Result: = 0;
End;
Procedure Tform1.button1click (sender:tobject);
var
id:dword
Begin
If Htimer = 0 Then Htimer: = CreateWaitableTimer (nil, True, nil);
CreateThread (nil, 0, @MyThreadFun, nil, 0, ID);
End;
Procedure Tform1.button2click (sender:tobject);
Begin
Cancelwaitabletimer (htimer);
End;
Procedure Tform1.formdestroy (sender:tobject);
Begin
CloseHandle (Htimer);
End;
End.
Form file:
object Form1: TForm1
Left = 0
Top = 0
Caption = 'Form1'
ClientHeight = 86
ClientWidth = 256
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = False
PixelsPerInch = 96
TextHeight = 13
object Button1: TButton
Left = 23
Top = 32
Width = 97
Height = 25
Caption = #21551#21160#23450#26102#22120
TabOrder = 0
OnClick = Button1Click
end
object Button2: TButton
Left = 134
Top = 32
Width = 97
Height = 25
Caption = #21462#28040#23450#26102#22120
TabOrder = 1
OnClick = Button2Click
end
end