线程安全退出 VS PostMessage,SendMessage的区别
說明:
?
SendMessage
函數功能:該函數將指定的消息發送到一個或多個窗口。此函數為指定的窗口調用窗口程序,直到窗口程序處理完消息再返回。而函數PostMessage不同,將一個消息寄送到一個線程的消息隊列后立即返回。函數原型:LRESULT SendMessage(HWND hWnd,UINT Msg,WPARAM wParam,LPARAM IParam);
參數:
hWnd:其窗口程序將接收消息的窗口的句柄。如果此參數為HWND_BROADCAST,則消息將被發送到系統中所有頂層窗口,包括無效或不可見的非自身擁有的窗口、被覆蓋的窗口和彈出式窗口,但消息不被發送到子窗口。
Msg:指定被發送的消息。
wParam:指定附加的消息指定信息。
IParam:指定附加的消息指定信息。
返回值:返回值指定消息處理的結果,依賴于所發送的消息。
?
//*************************?? 窗體文件? *******************************
unit Main;
interface
uses
? Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
? Dialogs,MyThread, StdCtrls;
const
? WM_MYQUIT=WM_USER+101;
type
? TForm1 = class(TForm)
??? Label1: TLabel;
??? Button1: TButton;
??? procedure FormCreate(Sender: TObject);
??? procedure Button1Click(Sender: TObject);
? private
??? { Private declarations }
??? FThread:TMyThread;
? public
??? { Public declarations }
??? procedure MyQuit(var Msg:TMessage);message WM_MYQUIT;
? end;
var
? Form1: TForm1;
implementation
{$R *.dfm}
{ TForm1 }
procedure TForm1.Button1Click(Sender: TObject);
begin
? if Assigned(FThread) then
??? showmessage('存在')
? else
??? showmessage('不存在');
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
? FThread:=TMyThread.Create(False);
end;
procedure TForm1.MyQuit(var Msg: TMessage);
var
? BeginTime:DWORD;
begin
? BeginTime:=GetTickCount;
? if Assigned(FThread) then
? begin
??? FThread.Terminate;
??? if FThread.Suspended then
????? FThread.Resume;
?? //? 如果線程使用SendMessage發送消息后
??? //? 則 FThread.WaitFor;? 線程將一直等待下去,
??? //? 原因是:SendMessage一直在等待窗口程序處理完消息再返回 ,程序將出現一直等待,直到主線程退出
??? FThread.WaitFor;? //? 程序一直等待?直到線程退出
??? FThread.Free;
??? FThread:=nil;
? end;
? Label1.Caption:='運行時間: '+intTostr(GetTickCount-BeginTime);
end;
end.
?
//? *****************************?? 下面是簡單的線程類,主要用于給主窗體發送消息,通知結束線程? ************
unit MyThread;
interface
uses
? Classes,windows,Messages;
type
? TMyThread = class(TThread)
? private
??? { Private declarations }
? protected
??? procedure Execute; override;
? end;
implementation
uses Main;
{ Important: Methods and properties of objects in visual components can only be
? used in a method called using Synchronize, for example,
????? Synchronize(UpdateCaption);
? and UpdateCaption could look like,
??? procedure MyThread.UpdateCaption;
??? begin
????? Form1.Caption := 'Updated in a thread';
??? end; }
{ TMyThread }
procedure TMyThread.Execute;
begin
? // 發送消息給主窗口,通知結束該線程
? // SendMessage(Form1.Handle,WM_MYQUIT,0,0);
? PostMessage(Form1.Handle,WM_MYQUIT,0,0);
end;
end.
?
轉載于:https://www.cnblogs.com/xiaowangstream/archive/2009/11/03/1595347.html
總結
以上是生活随笔為你收集整理的线程安全退出 VS PostMessage,SendMessage的区别的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysqld 安装细节
- 下一篇: 为iptables开放新的网络端口