简体   繁体   English

如何使用TThread.Synchronize()来检索TEdit控件的文本?

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

How can I use TThread.Synchronize() to retrieve the text of a TEdit control. 如何使用TThread.Synchronize()来检索TEdit控件的文本。 Should I assign the TEdit text to a global variable or something? 我应该将TEdit文本分配给全局变量吗?

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: 其次,在创建线程时,在create方法中传递(callback)方法并使用它以线程安全的方式获取文本:

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). 正如David在评论中提到的那样,总是将UI部分与工作线程(以及所有业务逻辑)分开。 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. 即使在小型程序中,由于它们往往会随着时间的推移而增长,并且突然间您发现自己(或同事)处于不良状态,其中包含大量难以维护或理解的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM