如何使用TThread.Synchronize()
检索TEdit
控件的文本。我应该将TEdit
文本分配给全局变量吗?
答案 0 :(得分:3)
First, declare a method in your form that retrieves the text. This method can be called both from the main thread and a worker thread:
Type
TMyGetTextProc = procedure(var s: String) of object;
procedure TForm1.GetMyText(var myText: String);
begin
TThread.Synchronize(nil,
procedure
begin
myText := ATedit.Text;
end
);
end;
Secondly, when you create the thread, pass the (callback) method in the create method and use it to get the text in a thread safe manner:
Type
TMyThread = Class(TThread)
private
FGetTextCallback: TMyGetTextProc;
public
constructor Create(aGetTextProc: TMyGetTextProc);
...
end;
Note, you can also do the syncronization from your thread directly if you prefer that. The point is that you pass a callback method to the worker thread.
As David mention in comments, always separate the UI part from worker threads (and for all business logic as well). Even in small programs, since they tend to grow over time, and suddenly you find yourself (or a co-worker) in a bad position with lots of code that is hard to maintain or understand.