为什么Dispatcher.Invoke在此示例中不执行委托参数?

Gis*_*shu 1 .net c# wpf unit-testing

    [Test]
    public void A()
    {
        var d = Dispatcher.CurrentDispatcher;

        Action action = () => Console.WriteLine("Dispatcher invoked me!");

        var worker = new BackgroundWorker();
        worker.DoWork += SomeWork;

        //worker.RunWorkerAsync( (Action) delegate { Console.WriteLine("This works!"); } );
        worker.RunWorkerAsync((Action) delegate { d.Invoke(action); } );

        System.Threading.Thread.Sleep(2500);
    }

    private void SomeWork(object sender, DoWorkEventArgs e)
    {
        (e.Argument as Action)();
    }
Run Code Online (Sandbox Code Playgroud)

这段代码不会引发异常.同时,Dispatcher.Invoke不执行任何操作.我发现这很奇怪.

我将一个辅助方法提取到一个基础ViewModel中.工作线程使用此方法DoOnUIThread()来避免线程关联问题.但是在我的单元测试中,我发现由于上述问题,尝试测试视图模型对象会导致失败.

我可以将整个行为移到可插入的依赖项中,我可以在测试中替换它.例如,ViewModelBase依赖于UIThreadExecutor.Execute(Action),我使用一个假的,只是在我的测试中调用动作.但是我很好奇为什么Dispatcher的行为方式如此......

Han*_*ant 5

当主线程空闲并重新进入分派循环时,Dispatcher只能执行其Begin/Invoke()任务.此时主线程处于静止状态,可以安全地执行调度的请求.以及Windows发送给它的任何通知.

在你的情况下它不是空闲的,它被困在Sleep(2500)内.