VCL线程同步的问题
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TMyThread = class(TThread)
private
procedure SetVisible;
protected
procedure Execute;override;
end;
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
FThread: TMyThread;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{ TMyThread }
procedure TMyThread.Execute;
begin
Form1.Button2.Visible := True;
//Synchronize(SetVisible);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Form1.Button2.Visible := False;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
FThread := TMyThread.Create(False);
end;
procedure TMyThread.SetVisible;
begin
Form1.Button2.Visible := True;
end;
end.
上面的代码Button2控件对应的windows对象会在线程结束时,无缘无故被destroy,导致窗口关闭时报错“句柄无效”。
这是为什么?使用同步却不会。
请讲的详细一点。
[解决办法]
我调试了一下,发现Form1.Button2.Visible := True;主要是调用代码:
procedure TControl.SetVisible(Value: Boolean);begin if FVisible <> Value then begin VisibleChanging; FVisible := Value; Perform(CM_VISIBLECHANGED, Ord(Value), 0); RequestAlign; end;end;