小编典典

在单元测试中使用WPF分派器

c#

在单元测试时,我无法让Dispatcher运行我传递给它的委托。当我运行程序时,一切正常,但是,在单元测试期间,以下代码将无法运行:

this.Dispatcher.BeginInvoke(new ThreadStart(delegate
{
    this.Users.Clear();

    foreach (User user in e.Results)
    {
        this.Users.Add(user);
    }
}), DispatcherPriority.Normal, null);

我在viewmodel基类中有以下代码来获取Dispatcher:

if (Application.Current != null)
{
    this.Dispatcher = Application.Current.Dispatcher;
}
else
{
    this.Dispatcher = Dispatcher.CurrentDispatcher;
}

我需要做一些事情来初始化Dispatcher进行单元测试吗?分派器从不运行委托中的代码。


阅读 486

收藏
2020-05-19

共1个答案

小编典典

通过使用Visual Studio单元测试框架,您无需自己初始化Dispatcher。完全正确,调度程序不会自动处理其队列。

您可以编写一个简单的帮助程序方法“ DispatcherUtil.DoEvents()”,该方法告诉Dispatcher处理其队列。

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)中 找到此类。

2020-05-19