在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, system.SyncObjs; type TForm1 = class(TForm) Button1: TButton; Button2: TButton; Memo1: TMemo; CheckBox1: TCheckBox; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure CheckBox1Click(Sender: TObject); private public { Public declarations } end; TMyThread = class(TThread) protected procedure Execute; override; end; var Form1: TForm1; AEvent: TEvent; MyThread: TMyThread; implementation {$R *.dfm} procedure Log(Msg: string); begin TThread.Synchronize(nil, procedure begin Form1.Memo1.Lines.Add(Msg); end); end; { TMyThread } procedure TMyThread.Execute; begin while not Terminated do begin AEvent.Acquire; Log(DateTimeToStr(Now)); TThread.Sleep(500); end; Log('Exit'); end; procedure TForm1.Button1Click(Sender: TObject); begin AEvent.SetEvent; end; procedure TForm1.Button2Click(Sender: TObject); begin AEvent.ResetEvent; end; procedure TForm1.CheckBox1Click(Sender: TObject); begin MyThread.Terminate; end; procedure TForm1.FormCreate(Sender: TObject); begin Memo1.Clear; AEvent := TEvent.Create(nil, False, False, ''); MyThread := TMyThread.Create(False); end; procedure TForm1.FormDestroy(Sender: TObject); begin if not MyThread.Finished then begin //确保线程正常退出 MyThread.Terminate; AEvent.SetEvent; MyThread.WaitFor; end; MyThread.Free; AEvent.Free; end; end.
AEvent := TEvent.Create(nil, False, False, '');
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论