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;