TThread.Synchronize()如何工作? [英] How does TThread.Synchronize() work?

查看:97
本文介绍了TThread.Synchronize()如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I tested the following code with the Synchronize() method in C++Builder 2010:

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

发生的事情是UI冻结,并且没有创建文件夹。这是否意味着 Synchronize()将代码传递给UI线程以执行它,然后等到代码执行后再继续?

What happened is that the UI freezed, and the folder was not created. 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?

编辑:

我错误地解释了我所做的工作我的测试代码。我真正完成的工作如下:

I explained wrongly what I have done in my test code. What I have really done is the following:

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

while(true) {}

并在调用 Synchronize()之后,我有以下代码:

And after calling Synchronize(), I had the following code:

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


推荐答案


这意味着Synchronize()将代码传递给UI线程以执行它,然后等到代码执行后再继续?

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?

是。实际上,这在文档中进行了描述:

Yes. This is in fact described in the documentation:


在主线程中执行方法调用。

Executes a method call within the main thread.

同步使AMethod指定的调用使用$ b执行。 $ b主线程,从而避免了多线程冲突。 AThread
参数关联调用者线程。

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.

对于静态方法,可以使用AThread参数
将AMethod与任何线程关联。另外,如果不需要知道主线程
中调用者线程的信息,则可以将nil / NULL用作AThread参数

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.

在当前实现中,Synchronize方法可以使用
关联的线程信息来唤醒Windows
平台上的主线程。

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

如果您不确定方法调用是否是线程安全的,请在Synchronize方法中从
对其进行调用以确保它在主
线程中执行。

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.

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

Your infinite loop is therefore blocking the main thread. And indeed the worker thread.

这篇关于TThread.Synchronize()如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆