In delphi XE I can use the start procedure, but this method does not exist in delphi 2007.
This sample code works ok in delphi xe, using Start
MyThread:=TMyThread.Create(True);
MyThread.FreeOnTerminate :=True;
MyThread.Property1:=900;
MyThread.Property2:=2;
MyThread.Start;
but in delphi 2007 the start
procedure does not exist, so I am using the resume procedure which is deprecated in the new versions of delphi.
MyThread:=TMyThread.Create(True);
MyThread.FreeOnTerminate :=True;
MyThread.Property1:=900;
MyThread.Property2:=2;
MyThread.Resume;
Is it ok use resume
in delphi 2007 or I must use another way to start a suspended thread?
In this context, a suspended thread is a thread whose execution has been explicitly paused (or suspended), i.e. it's context is no longer being executed but has been suspended to be resumed at some later point. This technique is primarily used by debuggers and is not recommended for sychronization activities.
The correct way to start a suspended thread is to never have a suspended thread in the first place.
There's a better way to create threads. If the caller must provide a value to the object in order for the class to work correctly, then don't make it optional: Require it as a parameter to the constructor. And if there's only one valid value for that parameter, then don't even make it a parameter: Just hard-code it in the constructor. (How many times have you written a thread class that only sometimes should free itself on termination? I've never seen that.)
constructor TMyThread.Create(Prop1, Prop2: Integer);
begin
inherited Create(False);
FreeOnTerminate := True;
Property1 := Prop1;
Property2 := Prop2;
end;
Then you can use the Ron Popeil method of creating threads: Just set it and forget it!
MyThread := TMyThread.Create(900, 2);
The caller doesn't have to do anything with the thread after creating it. And since it's a free-on-terminate thread, it's possible that the caller shouldn't even keep a reference to the MyThread
variable at all since the reference will become invalid as soon as the thread finishes running.
(Worried about that inherited Create(False)
line creating a thread that's going to start running before the rest of the constructor finishes running? Don't be! That was fixed in Delphi 6, over a decade ago. The thread will automatically start itself after the constructor finishes; see TThread.AfterConstruction
to see how.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With