WinRT - MessageDialog.ShowAsync将在我的自定义类中抛出UnauthorizedAccessException

glo*_*ver 11 .net c# unauthorizedaccessexcepti messagedialog windows-runtime

我想编写自己的控件,当调用ctor时,会显示一个MessageBox.

public class Class1
{
    public Class1()
    {
        ShowDialog();
    }
    void ShowDialog()
    {
        SynchronizationContext context = SynchronizationContext.Current;
        if (context != null)
        {
            context.Post((f) =>
            {
                MessageDialog dialog = new MessageDialog("Hello!");
                dialog.ShowAsync();
            }, null);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我的类被某人使用,并编写如下代码,则始终会抛出UnauthorizedAccessException dialog.ShowAsync();

void MainPage_Loaded(object sender, RoutedEventArgs e)
        {

            ClassLibrary1.Class1 c1 = new ClassLibrary1.Class1();
            MessageDialog dialog1 = new MessageDialog("");
            dialog1.ShowAsync();
        }
Run Code Online (Sandbox Code Playgroud)

有没有办法毫无例外地显示消息对话框?


我找到了一种方式,享受它!

Task ShowDialog()
        {
            CoreDispatcher dispatcher = Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher;
            Func<object, Task<bool>> action = null;
            action = async (o) =>
            {
                try
                {
                    if (dispatcher.HasThreadAccess)
                        await new MessageDialog("Hello!").ShowAsync();
                    else
                    {
                        dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                        () => action(o));
                    }
                    return true;
                }
                catch (UnauthorizedAccessException)
                {
                    if (action != null)
                    {
                        Task.Delay(500).ContinueWith(async t => await action(o));
                    }
                }
                return false;
            };
            return action(null);
        }
Run Code Online (Sandbox Code Playgroud)

Lew*_*nge 3

由于MessageDialogue需要在UI线程上运行,您可以尝试将其切换为:

var dispatcher = Windows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher;
dispatcher.RunAsync(DispatcherPriority.Normal, <lambda for your code which should run on the UI thread>);
Run Code Online (Sandbox Code Playgroud)