且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在单元测试中使用 WPF Dispatcher

更新时间:2023-02-21 09:40:49

通过使用 Visual Studio 单元测试框架,您无需自己初始化 Dispatcher.您说得对,Dispatcher 不会自动处理其队列.

By using the Visual Studio Unit Test Framework you don’t need to initialize the Dispatcher yourself. You are absolutely right, that the Dispatcher doesn’t automatically process its queue.

您可以编写一个简单的辅助方法DispatcherUtil.DoEvents()",它告诉 Dispatcher 处理其队列.

You can write a simple helper method "DispatcherUtil.DoEvents()" which tells the Dispatcher to process its queue.

C# 代码:

public static class DispatcherUtil
{
    [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
    public static void DoEvents()
    {
        DispatcherFrame frame = new DispatcherFrame();
        Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background,
            new DispatcherOperationCallback(ExitFrame), frame);
        Dispatcher.PushFrame(frame);
    }

    private static object ExitFrame(object frame)
    {
        ((DispatcherFrame)frame).Continue = false;
        return null;
    }
}

您也可以在 WPF 应用程序框架 (WAF) 中找到此类>.

You find this class too in the WPF Application Framework (WAF).