本文介绍了Windows 本机 API 是否支持计时器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Windows 本机 API 是否支持计时器?

Does the Windows native API support timers?

我知道 Windows 上的 POSIX 实现支持计时器,但我对 Windows SDK API 感兴趣.

I am aware that POSIX implementations on Windows support timers, but I am interested in Windows SDK APIs.

推荐答案

在 POSIX 计时器的上下文中回答这个问题是一个棘手的问题.Window API SetTimer 在依赖于线程的消息队列调度机制的 GUI 线程上创建一个计时器 - 这意味着您正在调用 GetMessage/DispatchMessage 的线程中的某个地方.

It's a tricky question to answer in the context of a POSIX timer. The Window API SetTimer creates a timer on a GUI thread that relies on the thread's message queue dispatching mechanism - which means somewhere in the thread you are calling GetMessage / DispatchMessage.

如果您正在编写非 GUI 代码,则必须实现消息循环是一种不自然的约束:- Windows 内核使用同步对象(代替信号)作为工作线程(即非 GUI)线程的一种方式对事件发出警报.CreateWaitiableTimer 将创建一个可以传递的句柄到工作线程中的 WaitForSingleObject/WaitForMultipleObjects.

If you are writing non-GUI code, having to implement a message loop is an unnatural constraint :- The Windows kernel uses synchronization objects (in place of signals) as a way for worker (i.e. non-GUI) threads to be alerted to events. CreateWaitiableTimer will create a handle that can be passed to WaitForSingleObject / WaitForMultipleObjects in a worker thread.

或者,您可以创建一个工作线程 - 在其中实现一个计时器(GUI 或内核),并在收到计时器信号时简单地调用您的(显然,它必须是线程安全的)对象.

Alternately, you can create a worker thread - implement a timer (GUI or kernel) in that, and simply call into your (obviously, it must be a thread-safe) object as the timer is signaled.

选择实际上取决于您的应用程序将如何与 POSIX 相似.

The choice really depends on exactly how POSIX-like your application is going to be.

这篇关于Windows 本机 API 是否支持计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-04 13:43