同一线程中各事件间的同步问题

wyj 2000-02-23 03:59:00
最近遇到一个问题,简化为下面的这段代码:

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls,Syncobjs;

const
MyMessage=WM_USER+200;

type
TForm1 = class(TForm)
Button1: TButton;
Label1: TLabel;
procedure Button1Click(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
private
Aborted:Boolean;
procedure HandleMessageLoop(var Mes:TMessage); Message MyMessage;
end;

var
Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.Button1Click(Sender: TObject);
begin
PostMessage(Form1.Handle,MyMessage,0,0);
end;

procedure TForm1.HandleMessageLoop(var Mes:TMessage);
var
i:Integer;
begin
if Mes.Msg=MyMessage then
begin
i:=1;
Aborted:=False;
while (i<=800) and (not Aborted) do
begin
Label1.Caption:=IntToStr(i);
Label1.Update;
Application.ProcessMessages;
Inc(i);
end;
end
else
Inherited;
end;

procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
Aborted:=True;
CanClose:=True;
end;

end.

简单来讲,Button1的功能是发消息,而HandleMessageLoop专用于处理这个消息。
由于按钮按下的时刻不可预见,就会造成HandleMessageLoop函数的重入,假如这个函数正在做比较重要的事情,就会造成混乱。
请问有什么较好的办法可能避免HandleMessageLooop函数在执行过程中被重入,如果不使用线程的话?
...全文
242 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
wyj 2000-02-23
  • 打赏
  • 举报
回复
谢谢各位,让俺试试再说...
Lin 2000-02-23
  • 打赏
  • 举报
回复
1、就如forgettor所说,用临界区;
2、设置全局变量,处理完后清除;
3、实际上是一回事。
wyj 2000-02-23
  • 打赏
  • 举报
回复
我曾用临界区试过,好象在同一线程中临界区并不起任何作用,既然K老师说了,那我就再试一枪
wyj 2000-02-23
  • 打赏
  • 举报
回复
不可以使用SENDMESSAGE,因为Buttton1Click并不是只用来发这一种消息的,它还要发送其它消息,由于各类消息的处理速度不同,因而不可以使用等待方式
kxy 2000-02-23
  • 打赏
  • 举报
回复
哦,那就用临界区,如顶楼所说:)
wyj 2000-02-23
  • 打赏
  • 举报
回复
BUTTON只是个简化对象,实际上是不可预见的
Lin 2000-02-23
  • 打赏
  • 举报
回复
procedure TForm1.Button1Click(Sender: TObject);
begin
Button1.Enabled := False;
//改PostMessage为SendMessage,因为SendMessage直到消息处理完才返回。
SendMessage(Form1.Handle,MyMessage,0,0);
Button1.Enabled := True;
end
kxy 2000-02-23
  • 打赏
  • 举报
回复
处理中button1.Enabled := False
forgettor 2000-02-23
  • 打赏
  • 举报
回复
Windows API:
InitiateCriticalSection;
EnterCriticalSection;
LeaveCriticalSection;

5,386

社区成员

发帖
与我相关
我的任务
社区描述
Delphi 开发及应用
社区管理员
  • VCL组件开发及应用社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧