【问题标题】:Returning a value from Dispatcher.RunAsync() to background thread从 Dispatcher.RunAsync() 返回一个值到后台线程
【发布时间】:2013-07-16 17:07:10
【问题描述】:

我正在使用 Dispatcher.RunAsync() 从后台线程显示 MessageDialog。但我无法弄清楚如何返回结果。

我的代码:

            bool response = false;

        await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
             async () =>
             {
                 DebugWriteln("Showing confirmation dialog: '" + s + "'.");
                 MessageDialog dialog = new MessageDialog(s);

                 dialog.Commands.Add(new UICommand(GetLanguageString("Util_DialogButtonYes"), new UICommandInvokedHandler((command) => {
                     DebugWriteln("User clicked 'Yes' in confirmation dialog");
                     response = true;
                 })));

                 dialog.Commands.Add(new UICommand(GetLanguageString("Util_DialogButtonNo"), new UICommandInvokedHandler((command) =>
                 {
                     DebugWriteln("User clicked 'No' in confirmatoin dialog");
                     response = false;
                 })));
                 dialog.CancelCommandIndex = 1;
                 await dialog.ShowAsync();
             });
        //response is always False
        DebugWriteln(response);

有没有办法做到这一点? 我想过可能会从 RunAsync() 内部返回值,但函数是无效的。

【问题讨论】:

  • 你应该尽量避免CoreDispatcher.RunAsync。该方法使您的 UI 线程像您的后台线程使用的“服务”。更简洁的设计是让您的后台线程成为您的 UI 线程使用的“服务”。那么你只需要async/await 并且根本不需要手动调度委托。
  • 我必须同意斯蒂芬的观点。我发布的代码来自用 VS2010 编写的 SL 应用程序,因此我无法访问 async/await(一旦我开始在 VS2012 中开发新的 SL 应用程序,我发现该方法没有用处)。也就是说,在另一个线程中不时地从 UI 中获取偶尔的文本框值或其他内容仍然是有益的。

标签: c# .net windows-store-apps


【解决方案1】:

您可以使用ManualResetEvent 类。

这是我将值从 UI 线程返回到其他线程的辅助方法。 这是为 Silverlight 准备的!因此,您可能无法将其复制粘贴到您的应用程序并期望它能够正常工作,但希望它能给您一个关于如何进行。

    public static T Invoke<T>(Func<T> action)
    {
        if (Dispatcher.CheckAccess())
            return action();
        else
        {
            T result = default(T);
            ManualResetEvent reset = new ManualResetEvent(false);
            Dispatcher.BeginInvoke(() =>
            {
                result = action();
                reset.Set();
            });
            reset.WaitOne();
            return result;
        }
    }

【讨论】:

  • 很好,请查看 Xyroids 对我的 c# 原件的评论。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多