我提供的
WaitOneAndPump
版本使用
DispatcherHooks
事件和
MsgWaitForMultipleObjectsEx
,以避免运行
繁忙等待循环。
但是需要注意,在生产代码中使用此
WaitOneAndPump
(或任何其他嵌套消息循环变体)几乎总是一个错误的设计决策。我只能想到两个合法使用嵌套消息循环的.NET API:
Window.ShowDialog
和
Form.ShowDialog
。
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
namespace Wpf_21642381
{
#region MainWindow
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Loaded += MainWindow_Loaded;
}
async void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
await Dispatcher.Yield(DispatcherPriority.ApplicationIdle);
try
{
Func<Task> doAsync = async () =>
{
await Task.Delay(6000);
};
var task = doAsync();
var handle = ((IAsyncResult)task).AsyncWaitHandle;
var startTick = Environment.TickCount;
handle.WaitOneAndPump(5000);
MessageBox.Show("Lapse: " + (Environment.TickCount - startTick));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
#endregion
#region WaitExt
public static class WaitExt
{
public static bool WaitOneAndPump(this WaitHandle handle, int millisecondsTimeout)
{
using (var operationPendingMre = new ManualResetEvent(false))
{
var result = false;
var startTick = Environment.TickCount;
var dispatcher = Dispatcher.CurrentDispatcher;
var frame = new DispatcherFrame();
var handles = new[] {
handle.SafeWaitHandle.DangerousGetHandle(),
operationPendingMre.SafeWaitHandle.DangerousGetHandle() };
DispatcherOperation idleOperation = null;
Action idleAction = () => { idleOperation = null; };
Action enqueIdleOperation = () =>
{
if (idleOperation != null)
idleOperation.Abort();
idleOperation = dispatcher.BeginInvoke(
idleAction,
DispatcherPriority.ApplicationIdle);
};
Func<uint> getTimeout;
if (Timeout.Infinite == millisecondsTimeout)
getTimeout = () => INFINITE;
else
getTimeout = () => (uint)Math.Max(0, millisecondsTimeout + startTick - Environment.TickCount);
DispatcherHookEventHandler onOperationPosted = (s, e) =>
{
operationPendingMre.Set();
};
DispatcherHookEventHandler onOperationCompleted = (s, e) =>
{
Debug.Assert(Thread.CurrentThread == dispatcher.Thread);
var nativeResult = WaitForSingleObject(handles[0], 0);
if (nativeResult == WAIT_OBJECT_0)
result = true;
else if (nativeResult == WAIT_ABANDONED_0)
throw new AbandonedMutexException(-1, handle);
else if (getTimeout() == 0)
result = false;
else if (nativeResult == WAIT_TIMEOUT)
return;
else
throw new InvalidOperationException("WaitForSingleObject");
frame.Continue = false;
};
EventHandler onDispatcherInactive = (s, e) =>
{
operationPendingMre.Reset();
var timeout = getTimeout();
var nativeResult = MsgWaitForMultipleObjectsEx(
(uint)handles.Length, handles,
timeout,
QS_EVENTMASK,
MWMO_INPUTAVAILABLE);
if (nativeResult == WAIT_OBJECT_0)
result = true;
else if (nativeResult == WAIT_TIMEOUT)
result = false;
else if (nativeResult == WAIT_ABANDONED_0)
throw new AbandonedMutexException(-1, handle);
else if (nativeResult == WAIT_OBJECT_0 + 1)
return;
else if (nativeResult == WAIT_OBJECT_0 + 2)
{
if (getTimeout() > 0)
{
enqueIdleOperation();
return;
}
result = false;
}
else
throw new InvalidOperationException("MsgWaitForMultipleObjectsEx");
frame.Continue = false;
};
dispatcher.Hooks.OperationCompleted += onOperationCompleted;
dispatcher.Hooks.OperationPosted += onOperationPosted;
dispatcher.Hooks.DispatcherInactive += onDispatcherInactive;
try
{
enqueIdleOperation();
Dispatcher.PushFrame(frame);
}
finally
{
if (idleOperation != null)
idleOperation.Abort();
dispatcher.Hooks.OperationCompleted -= onOperationCompleted;
dispatcher.Hooks.OperationPosted -= onOperationPosted;
dispatcher.Hooks.DispatcherInactive -= onDispatcherInactive;
}
return result;
}
}
const uint QS_EVENTMASK = 0x1FF;
const uint MWMO_INPUTAVAILABLE = 0x4;
const uint WAIT_TIMEOUT = 0x102;
const uint WAIT_OBJECT_0 = 0;
const uint WAIT_ABANDONED_0 = 0x80;
const uint INFINITE = 0xFFFFFFFF;
[DllImport("user32.dll", SetLastError = true)]
static extern uint MsgWaitForMultipleObjectsEx(
uint nCount, IntPtr[] pHandles,
uint dwMilliseconds, uint dwWakeMask, uint dwFlags);
[DllImport("kernel32.dll")]
static extern uint WaitForSingleObject(IntPtr hHandle, uint dwMilliseconds);
}
#endregion
}
这段代码没有经过严格测试,可能存在错误,但根据问题描述,我认为我已经掌握了正确的概念。