加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 17:51:13 所属栏目:百科 来源:网络整理
导读:我想编写自己的控件,当调用ctor时,会显示一个MessageBox. public class Class1{ public Class1() { ShowDialog(); } void ShowDialog() { SynchronizationContext context = SynchronizationContext.Current; if (context != null) { context.Post((f) = { M
我想编写自己的控件,当调用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>);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读