【发布时间】:2013-12-21 23:04:41
【问题描述】:
我有一个用 C# 编写的托管组件,它由旧版 Win32 应用程序作为 ActiveX 控件托管。在我的组件内部,我需要能够获得通常是 Application.Idle 事件,即获取 UI 线程上空闲处理时间的时间片(它必须是主 UI 线程)。
但是在这种托管方案中,Application.Idle 不会被触发,因为没有托管消息循环(即,没有 Application.Run)。
遗憾的是,主机也没有实现IMsoComponentManager,这可能适合我的需要。由于许多充分的理由,冗长的嵌套消息循环(使用Application.DoEvents)不是一种选择。
到目前为止,我能想到的唯一解决方案是使用普通的Win32 timers。
据此(现已灭亡)MSKB article,WM_TIMER 具有最低优先级之一,其次是 WM_PAINT,这应该让我尽可能接近空闲。
我是否错过了这种情况的任何其他选项?
这是一个原型代码:
// Do the idle work in the async loop
while (true)
{
token.ThrowIfCancellationRequested();
// yield via a low-priority WM_TIMER message
await TimerYield(DELAY, token); // e.g., DELAY = 50ms
// check if there is a pending user input in Windows message queue
if (Win32.GetQueueStatus(Win32.QS_KEY | Win32.QS_MOUSE) >> 16 != 0)
continue;
// do the next piece of the idle work on the UI thread
// ...
}
// ...
static async Task TimerYield(int delay, CancellationToken token)
{
// All input messages are processed before WM_TIMER and WM_PAINT messages.
// System.Windows.Forms.Timer uses WM_TIMER
// This could be further improved to re-use the timer object
var tcs = new TaskCompletionSource<bool>();
using (var timer = new System.Windows.Forms.Timer())
using (token.Register(() => tcs.TrySetCanceled(), useSynchronizationContext: true))
{
timer.Interval = delay;
timer.Tick += (s, e) => tcs.TrySetResult(true);
timer.Enabled = true;
await tcs.Task;
timer.Enabled = false;
}
}
我认为Task.Delay 不适合这种方法,因为它使用内核计时器对象,这些对象独立于消息循环及其优先级。
更新,我又找到了一个选项:WH_FOREGROUNDIDLE/ForegroundIdleProc。看起来和我需要的完全一样。
更新,我还发现 WPF 的 Win32 计时器技巧 is used 用于低优先级调度程序操作,即 Dispatcher.BeginInvoke(DispatcherPriority.Background, ...):
【问题讨论】:
标签: c# .net winforms com async-await