Delphi 操作多线程的代码, 在项目中需要在webservice中使用多线程,程序思想如下:
1.就创建一个线程, 也就是说有两个线程,主线程和创建的线程, 主线程用于程序的别的操作,例如停止服务,和关闭程序等等。
2.辅线程用于调用Webservice,用他的目的,还有就是方便查看memo中的日志, 如果只有一个线程,这是不可能的,只有等调用结束才可以,但是这里面又用到了Timer,结果想在主线程查看memo,很费劲。故创建一个辅线程。
type
TMyThread = class(TThread)
private
FMyThreadExecfinish: Boolean;
FHTTPRIOLeExp: THTTPRIO;
FHTTPRIONC: THTTPRIO;
FHTTPRIOLeExp2: THTTPRIO;
FHTTPRIOLeExp3: THTTPRIO;
function ExecTimer: Boolean;
protected
FLogStrings: TStrings;
procedure Execute; override;
public
property LogStrings: TStrings read FLogStrings write FLogStrings;
property MyThreadExecfinish: Boolean read FMyThreadExecfinish write FMyThreadExecfinish;
property HTTPRIOLeExp: THTTPRIO read FHTTPRIOLeExp write FHTTPRIOLeExp;
property HTTPRIONC: THTTPRIO read FHTTPRIONC write FHTTPRIONC;
property HTTPRIOLeExp2: THTTPRIO read FHTTPRIOLeExp2 write FHTTPRIOLeExp2;
property HTTPRIOLeExp3: THTTPRIO read FHTTPRIOLeExp3 write FHTTPRIOLeExp3;
end;
procedure TfrmDataExchangePlatformMain.FormShow(Sender: TObject);
begin
MyThread := TMyThread.Create(True); // false 则自动调用Execute, True, 需要Resume后,在调用Execute
MyThread.LogStrings := cxMemo_Log.Lines;
MyThread.MyThreadExecfinish := True;
MyThread.HTTPRIOLeExp := DMConn.HTTPRIOLeExp;
MyThread.HTTPRIONC := DMConn.HTTPRIONC;
end;
procedure TfrmDataExchangePlatformMain.Timer_ServiceTimer(Sender: TObject);
var
ID: THandle;
begin
if MyThread.MyThreadExecfinish then
MyThread.Resume;
//CreateThread(nil, 0, @ExecTimer, nil, 0, ID); //ExecTimer;
end;
{ TMyThread }
procedure TMyThread.Execute;
begin
inherited;
//FreeOnTerminate := True; {这可以让线程执行完毕后随即释放} 这个就不能要了, 因为你需要这个线程,在程序结束的时候把线程关闭就可以了
if MyThreadExecfinish then
ExecTimer;
end;
function TMyThread.ExecTimer: Boolean;
begin
Result := False ;
FMyThreadExecfinish := False;
Screen.Cursor := crHourGlass;
CoInitialize(nil);
try
TranspondClientBaseData_factory1(HTTPRIOLeExp, HTTPRIONC, LogStrings);
Sleep(1000);
TranspondPersonBaseData_factory1(HTTPRIOLeExp, HTTPRIONC, LogStrings);
Sleep(1000);
TranspondDeptBaseData_factory1(HTTPRIOLeExp, HTTPRIONC, LogStrings);
finally
Result := True;
FMyThreadExecfinish := True;
Screen.Cursor := crDefault;
CoUninitialize;
end;
end;