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

前端之家收集整理的这篇文章主要介绍了c# – WinRT – MessageDialog.ShowAsync将在我的自定义类中抛出UnauthorizedAccessException前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想编写自己的控件,当调用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);
        }
    }
}

如果我的类被某人使用,并且写下如下代码,则会在dialog.ShowAsync()中抛出UnauthorizedAccessException异常.

void MainPage_Loaded(object sender,RoutedEventArgs e)
        {

            ClassLibrary1.Class1 c1 = new ClassLibrary1.Class1();
            MessageDialog dialog1 = new MessageDialog("");
            dialog1.ShowAsync();
        }

有没有一种方法显示消息对话框?

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

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

解决方法

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

猜你在找的C#相关文章