Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
888 views
in Technique[技术] by (71.8m points)

multithreading - Which is the correct way to start a suspended thread in delphi 2007?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...