我想编写自己的控件,当调用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>);