Hi everyone.
Im sorry, i know there is a lot of post about threads.
But i really cant find my answer. Im sure the answer is there, if I can assemble the puzzle. But i cant, probably because im (sorta) new on this world. Im still learning and adding new concepts in my head.
I have this program with several buttons that runs a Tprocess, each one with differents Parameters. This tprocess is in a created Thread so my app doesn't freeze while is waiting for this process to finish (i read about Application.ProcessMessages, but i think this is a good oportunity to learn about Threads, so i decided to do it this way).
This is my code so far (this is a simplified version of the code, and im just showing the relevant parts of it):
MyThread = class(Tthread)
protected
procedure Execute; override;
end;
TForm1 = class(TForm)
procedure MyProcedure(ASender : TObject);
procedure ButtonClick(ASender : TObject);
private
public
end;
var
MyProcess: TProcess;
L: TlistStrings;
Combo: TcomboBox;
implementation
uses
{$R *.frm}
{ TForm1 }
procedure ButtonClick(ASender : TObject);
var
Thread: MyThread;
begin
thread := MyThread.Create(True);
thread.OnTerminate:= @MyProcedure;
thread.FreeOnTerminate:= True ;
thread.Start;
end;
procedure MyThread.Execute;
begin
Try
MyProcess:= TProcess.Create(nil);
MyProcess.Executable := 'program.exe';
MyProcess.Parameters.Add('parameter1');
MyProcess.Options := MyThread.Options + [powaitonexit, ponoconsole, pousepipes];
MyProcess.Execute;
L := TStringList.Create;
L.LoadFromStream(MyProcess.Output);
finally
MyProcess.Free;
end;
end;
procedure MyProcedure(ASender : TObject);
begin
try
Combo.items.AddStrings(L);
finally
L.Free
end;
end;
As you can see, is very simple:
You click "Button", it start the Thread, and set it to go to "MyPocedure" on terminate.
The thread starts, do what it has to do, and stores the result on a ListString.
Then, the last procedure, takes that ListString and use it to fill a combobox.
Easy peasy.
As i said, im not have just one button, but several. And all of them needs to use the same process, but with different parameters. And, some also would need to use another procedure after the Thread.
What i want to know is if i can REUSE the same Thread, more specifically the same MyThread.Execute procedure, but changing the Parameters, so i can save a lot of code writing.
My questions are: What is the correct way to do it? Should i create a unique Thread for all of them? It is (technically speaking) correct to reuse the Same Thread? How can i pass different parameters to the same "MyProcess"?
I know is a basic question (actually, right know im thinking a few ways to do it), but since im founding the bases of my learning right now, i want you to tell me the CORRECT way to do this.
I hope you can help me. Thank you in advance