WPF:如何同步调用 Dispatcher.Invoke()? [英] WPF: How to make Calls to Dispatcher.Invoke() Synchronous?

查看:71
本文介绍了WPF:如何同步调用 Dispatcher.Invoke()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我基于 MVVM 的 Wix Managed Bootstrapper 应用程序中,在处理不同的事件时,我试图向用户显示一个视图以获取一些输入.看起来 Burn 事件正在异步执行,因为使用 Dispatcher.Invoke(),它跳过或通过视图并点击最后一个事件,即不等待此输入​​任务完成.

In my MVVM based Wix Managed Bootstrapper application, while handling different events, I'm trying to show the user a view to get some input. It looks like Burn events are executing Asynchronously because using Dispatcher.Invoke(), it is skipping or passing by the view and hitting the last event, i.e not waiting for this input task to finish.

这是在点击最后一个之前需要完成的事件处理程序:

Here is the event handler which needs to finish before hitting last one:

请注意,当 MessageBox.Show 弹出时,它会等到我们关闭它.在调试时,我看到它实际上切换到 MissingSourceView 并加载了 MissingSourceViewModel,但随后跳过它,并执行 ApplyComplete();

BootstrapperApplication.ResolveSource += (sender, e) => {
                        System.Windows.Forms.MessageBox.Show("Inside ResolveSource");

                     WixBootstrapperData.CurrentDispatcher.Invoke(((Action)(() =>
                        {
                            WixBootstrapperData.CurrentViewModel = new MissingSourceViewModel(WixBootstrapperData, InfoMessage);
                        })));
                    };


BootstrapperApplication.ApplyComplete += (sender, e) =>
            {               
                WixBootstrapperData.BootstrapperApplicationModel.FinalResult = e.Status;
                WixBootstrapperData.CurrentDispatcher.Invoke((Action)(() =>
                {
                  InfoMessage = AppResource.MsgFinished;
                  WixBootstrapperData.CurrentViewModel = new FinishViewModel(WixBootstrapperData, InfoMessage);
                }
                ));
            };

我想,我应该将 await 和 async 与 ResolveSource() 一起使用,但是我面临如下错误:

I guess, I should use await and async with ResolveSource(), but I face errors like:

错误 CS1061 'BaseViewModel' 不包含定义'GetAwaiter' 和没有扩展方法 'GetAwaiter' 接受第一个可以找到任务"类型的参数(您是否缺少使用指令或程序集引用?)

Error CS1061 'BaseViewModel' does not contain a definition for 'GetAwaiter' and no extension method 'GetAwaiter' accepting a first argument of type 'Task' could be found (are you missing a using directive or an assembly reference?)

知道如何让它在 ResolveSource() 中等待完成,然后跳转到它想要的任何地方吗?

Any idea how to make it wait for finishing inside ResolveSource() and then jump to wherever it wants?

推荐答案

使用它,请告诉它是否能解决您的问题.

Use this, and please tell if this solves your problem.

        WixBootstrapperData.CurrentDispatcher.Invoke(((Action)(() =>
        {
           Task.Factory.StartNew(() => {
              WixBootstrapperData.CurrentViewModel = new MissingSourceViewModel(WixBootstrapperData, InfoMessage);
           }).RunSynchronously();
        })));

这篇关于WPF:如何同步调用 Dispatcher.Invoke()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆