Returning a value from Dispatcher.RunAsync() to background thread

北慕城南 提交于 2020-01-13 13:32:17

问题


I'm using Dispatcher.RunAsync() to show a MessageDialog from a background thread. But I'm having trouble figuring out how to get a result returned.

My code:

            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);

Is there anyway to do it like this? I thought about maybe returning the value from inside RunAsync() but function is void.


回答1:


You could make use of the ManualResetEvent class.

This is my helper method for returning values from the UI thread to other threads. This is for Silverlight! As such, you probably can't copy-paste it to your application and expect it to work, BUT hopefully it'll give you an idea on how to proceed.

    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;
        }
    }


来源:https://stackoverflow.com/questions/17671597/returning-a-value-from-dispatcher-runasync-to-background-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!