简体   繁体   English

我什么时候需要在TThread中同步?

[英]When do I need synchronize in TThread?

I know that you need synchronize (yourprocedure) to set eg a label's text. 我知道您需要synchronize (yourprocedure)来设置例如标签的文本。 But what about: 但是关于:

  1. Reading a label's text. 阅读标签的文字。
  2. Toggle/Set the label's enabled property. 切换/设置标签的启用属性。
  3. Call other labels procedures/functions (eg onclick event). 调用其他标签程序/功能(例如onclick事件)。

Is there an easy rule to know/remember when I need to use synchronize ? 当我需要使用synchronize时,是否有一个简单的规则来了解/记住?

PS.: Is synchronize similar to PostMessage/SendMessage? PS。:同步类似于PostMessage / SendMessage吗?

Easy rule of thumb: ANY access to VCL UI components needs to be synchronized. 简单的经验法则:需要同步对VCL UI组件的 任何访问。 That includes both reading and writing of UI control properties. 这包括读取和写入UI控件属性。 Win32 UIs , most notably dialogs like MessageBox() and TaskDialog() , can be used directly in worker threads without synchronizing. Win32 UI ,尤其是MessageBox()TaskDialog()等对话框,可以直接在工作线程中使用而无需同步。

TThread.Synchronize() is similar to SendMessage() (in fact, it used to be implemented using SendMessage() internally in Delphi 5 and earlier). TThread.Synchronize()类似于SendMessage() (事实上​​,它曾经在Delphi 5及更早版本的内部使用SendMessage()实现)。 TThread.Queue() is similar to PostMessage() . TThread.Queue()类似于PostMessage()

Any time you access a VCL UI component, you need to implement some type of thread safety measure. 每次访问VCL UI组件时,都需要实现某种类型的线程安全措施。 This is also, typically, the case when you're accessing a variable or procedure that exists or will be accessed by another thread. 当您访问存在或将被另一个线程访问的变量或过程时,通常也是如此。 However, you don't need to use the Synchronize method in all of these situations. 但是,在所有这些情况下,您不需要使用Synchronize方法。 There are other tools at your disposal, and Synchronize is not always your best solution. 您可以使用其他工具,而Synchronize并不总是最佳解决方案。

Synchronize blocks both the main thread and the calling thread while it's performing the procedure that you pass to it, so overusing it can detract from the benefits of multi-threading. 在执行传递给它的过程时,同步阻塞主线程和调用线程,因此过度使用它会降低多线程的好处。 Synchronize is probably most commonly used for updating your UI, but if you find that you're having to use it really frequently, then it might not be a bad idea to check and see if you can restructure your code. 同步可能是最常用于更新UI的,但如果您发现必须经常使用它,那么检查并查看是否可以重构代码可能不是一个坏主意。 IE do you really need to read labels from within your thread? IE你真的需要从你的线程中读取标签吗? Can you read the label before starting the thread and pass it into the thread's constructor? 你可以在启动线程之前读取标签并将其传递给线程的构造函数吗? Can you handle any of these tasks in the thread's OnTerminate event handler? 你能在线程的OnTerminate事件处理程序中处理这些任务吗?

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

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