不知道楼主设计这个线程是不是为了防止SocketConnection在第一次连接时因为连接时间过长从而阻塞了主程序的运行?如果是这样可以把主线程的SocketConnection在线程Create时传到线程中去。以下是我曾经写过的一个简单的办法,用来防止第一次远程调用COM+时时间过长而客户端不能操作的情况,你可以参考一下:
.............
.............
TQueryThread=Class(TThread)
private
FCDSAuthors:TClientDataSet;
FCDSBooks:TClientDataSet;
FObjQuery:variant;//Com+对象
FAuthorsData:OleVariant;
FBooksData:OleVariant;
FStatusBar:TStatusBar;
FStr:string;//状态提示
protected
procedure Execute;override;
procedure UpdateCDS;
procedure UpdateSBar;//显示目前状态
public
//这儿传入主线程中的VCL
constructor Create(CDS1,CDS2:TClientDataSet;SBar:TStatusBar);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
const
MachineName:string='机器名';
var
hMutex:THandle=0;//互拆对象
constructor TQueryThread.Create(CDS1,CDS2:TClientDataSet;SBar:TStatusBar);
begin
FreeOnTerminate:=True;
FCDSAuthors:=CDS1;
FCDSBooks:=CDS2;
FStatusBar:=SBar;
inherited Create(False);
end;
procedure TQueryThread.Execute;
begin
if WaitForSingleObject(hMutex,0)=WAIT_OBJECT_0 then
begin
CoInitialize(nil);
FStr:='正在连接并获取数据........................';
try
try
//application.initialize;
Synchronize(UpdateSBar);
FObjQuery:=CoXTQuery.CreateRemote(MachineName);//这步需要较长时间,类似SocketConnection的连接
FObjQuery.GetAuthors_ForGUI('select * from authors',FAuthorsData);
FObjQuery.GetBooks_ForGUI('select * from Books',FBooksData);
FObjQuery:=null;
Synchronize(UpdateCDS);
FStr:='结束';
except
on Exceptiondo
FStr:='获取数据失败';
end;
finally
Synchronize(UpdateSBar);
CoUninitialize;
ReleaseMutex(hMutex);
end;
end;
end;
procedure TQueryThread.UpdateCDS ;
begin
try
FCDSAuthors.Data:=FAuthorsData;
FCDSBooks.Data:=FBooksData;
except
on Exceptiondo
showmessage('数据错误');
end;
end;
procedure TQueryThread.UpdateSBar;
begin
FStatusBar.Panels[0].Text:=FStr;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
hMutex:=CreateMutex(nil,False,nil);
application.initialize;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
CloseHandle(hMutex);
end;
//连接并获得数据
procedure TForm1.btnGetDataClick(Sender: TObject);
begin
TQueryThread.Create(CDSAuthors,CDSBooks,StatusBar1);
end;