TThread.Synchronize() 是如何工作的?

How does TThread.Synchronize() work?

我在 C++Builder 2010 中使用 Synchronize() 方法测试了以下代码:

while(true) {}
CreateDirectory ("D:\test", NULL);

发生的事情是 UI 冻结,并且未创建文件夹。那是不是说Synchronize()把代码交给UI线程去执行,然后等代码执行完了再继续?


编辑:

我在测试代码中错误地解释了我所做的事情。我真正做过的是:

我使用以下代码调用了 Synchronize()

while(true) {}

在调用 Synchronize() 之后,我得到了以下代码:

CreateDirectory ("D:\test", NULL);

Does that means that Synchronize() passes the code to the UI thread to execute it, and then waits until the code is executed before continuing?

是的。这实际上在 documentation:

中有描述

Executes a method call within the main thread.

Synchronize causes the call specified by AMethod to be executed using the main thread, thereby avoiding multithread conflicts. The AThread parameter associates the caller thread.

For static methods, you can associate AMethod with any thread using the AThread parameter. Also, you can use nil/NULL as AThread parameter if you do not need to know the information for the caller thread in the main thread.

In the current implementation, the Synchronize method can use associated thread information to wake-up the main thread on Windows platforms.

If you are unsure whether a method call is thread-safe, call it from within the Synchronize method to ensure that it executes in the main thread.

Execution of the current thread is suspended while the method executes in the main thread.

因此,您的无限循环阻塞了主线程。确实是工作线程。