简体   繁体   English

TThread :: Synchronize()>读取表单组件属性时?

[英]TThread::Synchronize() > when reading Form component properties?

My Environment: 我的环境:

  • C++ Builder XE4 C ++ Builder XE4
  • using VCL component 使用VCL组件

I have a question about TThread:Synchronize(). 我对TThread:Synchronize()有疑问。

Usually, I use Synchronize() when I update Form component (eg Text->Caption) from the TThread routine(). 通常,当我从TThread例程() 更新 Form组件(例如Text-> Caption)时,我会使用Synchronize()。

__fastcall TThreadSample::Execute()
{
    Synchronize(&updateFormText);
}

where the updateFormText() is a function to update Form Text->Caption. 其中updateFormText()是用于更新“表单文本”->“标题”的函数。

On the other hand, when I read caption from the Form text, I used followings without Synchronize(). 另一方面,当我从Form文本中读取标题时,我使用了以下没有Synchronize()的语句。

__fastcall TThreadSample::DoRead()
{
    String acap = CFormXXX::GetTextCaption();
}

void __fastcall CFormXXX::GetTextCaption()
{
    return FormXXX->TextXXX->Text;
}

Question: Do I have to use Synchronize() also when I read Form component properties from a TThread routine? 问:从TThread例程读取 Form组件属性时,是否还必须使用Synchronize()吗?

Yes . 是的

Properties are in fact syntactic sugar for function calls. 实际上,属性是函数调用的语法糖。 Reading one also means a function is called ( well, most of the time [1] ). 读一个也意味着一个函数被调用( 好吧,大多数时候 [1] )。

In other words, if, in your code, you do: 换句话说,如果您在代码中执行以下操作:

x = MyVCLObj->SomeProperty;

the C++Builder compiler in fact generates a call to the (usually private) getter function for the property: 实际上,C ++ Builder编译器会为该属性生成(通常是私有的)getter函数的调用:

x = MyVCLObj->GetSomeProperty();

That runs in the context of the main thread, so it must be accessed using Synchronize() . 它在主线程的上下文中运行,因此必须使用Synchronize()进行访问。


[1] I know that this is not true for all properties, and you may well be accessing the member field (eg FSomeProperty ) directly, but do you really want to check the docs each time? [1] 我知道并非所有属性都正确,您很可能直接访问成员字段(例如FSomeProperty ),但是您是否真的想每次检查文档? And this may change in a future version of the class too. 这可能会在该类的将来版本中更改。 So you should generally treat a property access like a function call. 因此,通常应将属性访问视为函数调用。

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

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