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.)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…