我有一個來自TThread的孩子。一切工作正常,但我怎麼做大量暫停或恢復我創建的線程?或者我怎樣才能暫停第二個線程(它是在Button2Click中創建的)?這裏是我的代碼的一部分:德爾福:如何處理動態創建的線程
TMyThread = class(TThread)
private
source_file, destination_file: string;
total_size, current_size, download_item_id: integer;
protected
procedure ShowResult;
procedure Execute; override;
public
end;
var
MyThread: TMyThread;
begin
procedure TMyThread.Execute;
begin
//Some code for download file here, it doesn't matter
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
MyThread := TMyThread.Create(True);
MyThread.source_file :='http://example.com/download1.zip';
MyThread.destination_file := 'c:\download1.zip';
MyThread.download_item_id := 0;
MyThread.Priority := tpNormal;
MyThread.FreeOnTerminate := True;
MyThread.Resume;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
MyThread := TMyThread.Create(True);
MyThread.source_file :='http://example.com/download2.zip';
MyThread.destination_file := 'c:\download2.zip';
MyThread.download_item_id := 1;
MyThread.Priority := tpNormal;
MyThread.FreeOnTerminate := True;
MyThread.Resume;
end;
end.
也就是說,如果我創建一個線程像這樣 - 這是爲我工作:
var
MyThread1, MyThread2: TMyThread;
...
procedure TForm1.Button1Click(Sender: TObject);
begin
MyThread1 := TMyThread.Create(True);
MyThread1.source_file :='http://example.com/download1.zip';
MyThread1.destination_file := 'c:\download1.zip';
MyThread1.download_item_id := 0;
MyThread1.Priority := tpNormal;
MyThread1.FreeOnTerminate := True;
MyThread1.Resume;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
MyThread2 := TMyThread.Create(True);
MyThread2.source_file :='http://example.com/download2.zip';
MyThread2.destination_file := 'c:\download2.zip';
MyThread2.download_item_id := 1;
MyThread2.Priority := tpNormal;
MyThread2.FreeOnTerminate := True;
MyThread2.Resume;
end;
//Terminate all of TMyThread
procedure TForm1.Button3Click(Sender: TObject);
begin
MyThread1.Terminate;
MyThread2.Terminate;
ShowMessage('All downloads were terminated!');
end;
//Terminate ONLY the second of TMyThread
procedure TForm1.Button4Click(Sender: TObject);
begin
MyThread2.Terminate;
ShowMessage('The second download was terminated!');
end;
但如何做到這一點的一組動態創建TMyThread的(如在第一個代碼示例中)?
使用['TThread.Start'](http://docwiki.embarcadero.com/Libraries/XE3/en/System.Classes.TThread.Start)代替'Resume'。不推薦使用「Resume」的警告消息必須這樣說。也不要訪問班級的「私人」成員,這就是爲什麼他們是私人的。而且,不要試圖用'Suspend'或其他東西來暫停*線程。如果您真的需要這樣做,請使用系統對象,例如事件,並等待它,例如通過使用'WaitForSingleObject'。 – TLama
感謝您的意見,但問題是:如何訪問動態創建的線程?我的意思是,它可能是一個大規模的'TThread.Terminate',不一定完全是'TThread.Suspend'或'TThread.Resume'。 –
請參閱[我應該用什麼德爾福代碼替換我的調用不推薦TThread方法掛起?](http://stackoverflow.com/q/2097316/576719)。事件是一個可以等待的對象。如果你的線程有一個全局事件,他們都可以等待。如果你需要分別控制你的線程,在一個自定義的'TThread.Create'中傳遞一個單獨的事件對象。 –