我想要写我自己的控制,调用构造函数时,会显示一个消息框。
公共类的Class1
{
公共Class1的()
{
的ShowDialog();
}
无效的ShowDialog()
{
SynchronizationContext的背景下= SynchronizationContext.Current;
如果(背景!= NULL)
{
context.Post((F)=>
{
MessageDialog对话框=新MessageDialog(你好!);
dialog.ShowAsync();
}, 空值);
}
}
}
如果我的类由一个人,写了codeS如下,UnauthorizedAccessException总是抛出 dialog.ShowAsync();
无效MainPage_Loaded(对象发件人,RoutedEventArgs E)
{
ClassLibrary1.Class1 C1 =新ClassLibrary1.Class1();
MessageDialog dialog1 =新MessageDialog();
dialog1.ShowAsync();
}
有没有一种方式来显示无一例外消息对话框?
我找到了一种方法,享受它!
任务的ShowDialog()
{
CoreDispatcher调度= Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher;
FUNC<对象,任务和LT;布尔>>行动= NULL;
行动=异步(0)=>
{
尝试
{
如果(dispatcher.HasThreadAccess)
等待新的MessageDialog(你好!)ShowAsync()。
其他
{
dispatcher.RunAsync(CoreDispatcherPriority.Normal,
()=>行动(O));
}
返回true;
}
赶上(UnauthorizedAccessException)
{
如果(动作!= NULL)
{
Task.Delay(500).ContinueWith(异步T =>等待行动(O));
}
}
返回false;
};
返回动作(空);
}
解决方案
由于MessageDialogue需要在UI线程上运行,你可以尝试切换到:
VAR调度= Windows.UI.Core.CoreWindow.GetForCurrentThread()调度。
dispatcher.RunAsync(DispatcherPriority.Normal,<拉姆达为您code应该运行在UI线程&GT的;);
I Want to write my own control, when the ctor is invoked, a MessageBox is shown.
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);
}
}
}
If my class is used by someone, and write the codes as below, UnauthorizedAccessException is always thrown in dialog.ShowAsync();
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
ClassLibrary1.Class1 c1 = new ClassLibrary1.Class1();
MessageDialog dialog1 = new MessageDialog("");
dialog1.ShowAsync();
}
Is there a way to show a message dialog without exception?
I found a way, enjoy it!
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);
}
解决方案
As MessageDialogue needs to run on the UI thread, can you try switching it to:
var dispatcher = Windows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher;
dispatcher.RunAsync(DispatcherPriority.Normal, <lambda for your code which should run on the UI thread>);