如何检测到已设置TEvent? [英] How do you detect that a TEvent has been set?

查看:59
本文介绍了如何检测到已设置TEvent?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Delphi XE2文档中有关TEvent的内容是这样的:

The Delphi XE2 documentation says this about TEvent:

有时,您需要等待线程完成某些操作,而不是等待特定线程完成执行.为此,请使用事件对象.应该在全局范围内创建事件对象(System.SyncObjs.TEvent),以便它们可以像对所有线程可见的信号一样起作用.

Sometimes, you need to wait for a thread to finish some operation rather than waiting for a particular thread to complete execution. To do this, use an event object. Event objects (System.SyncObjs.TEvent) should be created with global scope so that they can act like signals that are visible to all threads.

当一个线程完成其他线程所依赖的操作时,它将调用TEvent.SetEvent.SetEvent会打开信号,因此检查的其他任何线程都将知道该操作已完成.要关闭信号,请使用ResetEvent方法.

When a thread completes an operation that other threads depend on, it calls TEvent.SetEvent. SetEvent turns on the signal, so any other thread that checks will know that the operation has completed. To turn off the signal, use the ResetEvent method.

例如,考虑一种情况,您必须等待多个线程完成其执行,而不是单个线程.因为您不知道哪个线程将最后完成,所以不能简单地使用其中一个线程的WaitFor方法.相反,您可以让每个线程在完成时增加一个计数器,并通过设置一个事件来向最后一个线程发出信号,表明它们已全部完成.

For example, consider a situation where you must wait for several threads to complete their execution rather than a single thread. Because you don't know which thread will finish last, you can't simply use the WaitFor method of one of the threads. Instead, you can have each thread increment a counter when it is finished, and have the last thread signal that they are all done by setting an event.

但是,Delphi文档没有解释另一个线程如何检测到TEvent.Set事件被调用.您能解释一下如何检查是否调用了TEvent.Set吗?

The Delphi documentation does not, however, explain how another thread can detect that TEvent.Set event was called. Could you please explain how to check to see if TEvent.Set was called?

推荐答案

如果要测试是否已发出事件信号,请致电

If you want to test if an event is signaled or not, call the WaitFor method and pass a timeout value of 0. If the event is set, it will return wrSignaled. If not, it will time out immediately and return wrTimeout.

话虽如此,事件的正常用法不是检查事件是否以这种方式发出信号,而是通过阻塞当前线程直到发出事件信号来进行同步.您可以通过将一个非零值传递给timeout参数来执行此操作,如果可以确定常量将要完成并想等到它,则可以将常量 INFINITE 传递给该参数,如果不这样做,则可以传递一个较小的值不想无限期地阻塞.

Having said that, the normal usage of an event is not to check whether it's signaled in this manner, but to synchronize by blocking the current thread until the event is signaled. You do this by passing a nonzero value to the timeout parameter, either the constant INFINITE if you're certain that it will finish and you want to wait until it does, or a smaller value if you don't want to block for an indefinite amount of time.

这篇关于如何检测到已设置TEvent?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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