How to use TThread.Synchronize() to retrieve the text of a TEdit control?

237 views Asked by At

How can I use TThread.Synchronize() to retrieve the text of a TEdit control. Should I assign the TEdit text to a global variable or something?

1

There are 1 answers

0
LU RD On BEST ANSWER

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.