3

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() 内から値を返すことを考えましたが、関数は無効です。

4

1 に答える 1

4

ManualResetEventクラスを利用することができます。

これは、UI スレッドから他のスレッドに値を返すヘルパー メソッドです。これはシルバーライト用です!そのため、おそらくアプリケーションにコピー アンド ペーストして動作することを期待することはできませんが、続行する方法についてのアイデアが得られることを願っています。

    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;
        }
    }
于 2013-07-16T09:07:10.747 に答える