procedure TForm1.Button1Click(Sender: TObject); begin IfCon := 0; TThread.CreateAnonymousThread(MyMethod).Start; //执行线程,不会卡死
{if True=IfCon then //结果上面线程中的代码还没执行完,下面的代码已经一同执行下去了 showMessage('连接成功!') else showMessage('连接失败!')} while IfCon = 0 then begin Application.ProcessMessages; Sleep(200); end; if IfCon = 1 then showMessage('连接成功!') else showMessage('连接失败!'); end;
var Form1: TForm1; ifCon:integer; implementation{$R *.dfm} procedure MyMethod; begin Try if Form1.ADOConnection1.Connected then begin ifcon:=1 ; Form1.Canvas.TextOut(10,10,'第一'+IntToStr(iFcon)) ; end else begin Ifcon:=-1; Form1.Canvas.TextOut(30,30,'第二'+IntToStr(iFcon)); end; Except ifCon:=-1; Form1.Canvas.TextOut(50,50,'第三'+IntToStr(iFcon)); End; end;procedure TForm1.Button1Click(Sender: TObject); begin IfCon:=0; TThread.CreateAnonymousThread(MyMethod).Start; //!!! while IfCon=0 do begin Application.ProcessMessages; Sleep(200); end; if IfCon = 1 then showMessage('连接成功!') else showMessage('连接失败!'); Form1.Canvas.TextOut(70,70,'第四'+IntToStr(iFcon)); end;end.
连接代码我是写在了另一个wait窗体里面,用来显示一个滚动的gif,正在连接……。连接成功后,关闭wait窗体,再在主线程中判断是否连接成功,然后再执行下面的事件的。
IfCon: integer;procedure TForm1.MyMethod;
begin
Try
ADOQuery1.Open; //打开数据库连接
IfCon:=1;
Except
ifCon:=-1;
End;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
IfCon := 0;
TThread.CreateAnonymousThread(MyMethod).Start; //执行线程,不会卡死
{if True=IfCon then //结果上面线程中的代码还没执行完,下面的代码已经一同执行下去了
showMessage('连接成功!')
else
showMessage('连接失败!')} while IfCon = 0 then
begin
Application.ProcessMessages;
Sleep(200);
end; if IfCon = 1 then
showMessage('连接成功!')
else
showMessage('连接失败!');
end;
你的等待窗口模态化显示,然后等待线程给自己PostMessage是否连接成功等等
如果等待窗口被手动关闭,那么直接在等待窗体里去关闭连接线程即可
Form1: TForm1;
ifCon:integer;
implementation{$R *.dfm}
procedure MyMethod;
begin
Try
if Form1.ADOConnection1.Connected then
begin
ifcon:=1 ;
Form1.Canvas.TextOut(10,10,'第一'+IntToStr(iFcon)) ;
end
else
begin
Ifcon:=-1;
Form1.Canvas.TextOut(30,30,'第二'+IntToStr(iFcon));
end;
Except
ifCon:=-1;
Form1.Canvas.TextOut(50,50,'第三'+IntToStr(iFcon));
End;
end;procedure TForm1.Button1Click(Sender: TObject);
begin
IfCon:=0;
TThread.CreateAnonymousThread(MyMethod).Start; //!!!
while IfCon=0 do
begin
Application.ProcessMessages;
Sleep(200);
end;
if IfCon = 1 then
showMessage('连接成功!')
else
showMessage('连接失败!');
Form1.Canvas.TextOut(70,70,'第四'+IntToStr(iFcon));
end;end.