【问题标题】:Returns made by async Dispatcher Invoke not considered as return by method异步 Dispatcher Invoke 的返回不被视为方法返回
【发布时间】:2015-07-25 02:15:06
【问题描述】:

为了代码重用,我试图在通过调度程序调用后返回一个异步值,但该方法并未将其视为返回。为什么?

    internal static async Task<bool> iASK(string message, string title)
    {
        await Application.Current.Dispatcher.Invoke(async () =>
                    {
                        return await ASK(message, title);
                    });
        //throw new Exception("iASK's question didn't receive response.");
    }

在方法结束时抛出异常停止了方法的抱怨,但现在我只收到抛出的异常。


更新 1 异步方法是调用开源 MahApps MessageBox

    internal static async Task<bool> ASK(string message, string title)
    {
        return MahApps.Metro.Controls.Dialogs.MessageDialogResult.Affirmative == 
            await CustomShowMessage(message, title, MahApps.Metro.Controls.Dialogs.MessageDialogStyle.AffirmativeAndNegative, 
            new MahApps.Metro.Controls.Dialogs.MetroDialogSettings() { AffirmativeButtonText = "Yes", NegativeButtonText = "No" });
    }

MessageBox 在 UI 线程中运行,但在继续我的程序之前,我需要来自我的单独线程的响应。

我目前通过运行来调用它

                await System.Windows.Application.Current.Dispatcher.Invoke(async () =>
                {
                    await ASK(message, title);
                });

在我的主要方法中。我实现了 iASK 方法以简化代码重用。

我不知道如何通过 BeginInvoke 调用异步方法。

【问题讨论】:

  • 你根本不应该使用Invokeawait 的主要特性之一是延续都在调用者的上下文中运行,如果方法需要操作 UI,它应该是 UI 上下文。您应该只是从 UI 线程调用该方法,等待一些非 UI 工作,然后继续更新 UI。
  • @Servy 我在 MVVMLight 和 MahApps 之上构建了一个应用程序。我不确定如何在不破坏 MVVM 的情况下从 UI 上下文中调用任何内容。您是否知道任何“正确”的示例代码,它们实现了一个可能需要询问用户(通过异步消息框)同时保持 UI 流畅的程序?
  • 所有事件处理程序都将在 UI 线程中;您只需要不离开 UI 上下文。
  • (我已经删除了我的答案,因为你的答案基本上就是我最终要发布的内容。我仍然认为这不是一个非常干净的方法,但它确实有效......)跨度>
  • @JonSkeet Servy 我很想构建一个更简洁的方法,所以如果你在网络上找到任何正确实现异步编程的复杂代码,请给我一个链接。我目前无法识别什么是干净/不干净的。感谢您的帮助。

标签: c# wpf asynchronous async-await


【解决方案1】:

为了将来参考,我解决了它

    internal static async Task<bool> iASK(string message, string title)
    {
           return await Application.Current.Dispatcher.Invoke(async () =>
           {
                return await ASK(message, title);
           });
    //throw new Exception("iASK's question didn't receive response.");
    }

【讨论】:

    猜你喜欢
    • 2014-10-22
    • 2019-01-08
    • 1970-01-01
    • 1970-01-01
    • 2019-03-27
    • 1970-01-01
    • 2013-05-03
    • 2012-12-20
    • 2018-06-10
    相关资源
    最近更新 更多