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

问题描述

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

The Delphi XE2 documentation says this about TEvent:

当一个线程完成其他线程所依赖的操作时,它将调用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?

推荐答案

如果要测试是否已发出事件信号,请致电 WaitFor 方法并传递超时值0.如果设置了该事件,它将返回wrSignaled .如果没有,它将立即超时并返回 wrTimeout .

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-04 21:19