C# 使用任务时Windows Phone UnauthorizedAccessExection
我尝试使用任务对象异步运行代码:C# 使用任务时Windows Phone UnauthorizedAccessExection,c#,windows-phone-8,windows-phone,C#,Windows Phone 8,Windows Phone,我尝试使用任务对象异步运行代码: public void buttonAnswer_Click(object sender, RoutedEventArgs e) { Task t = new Task(() => { System.Threading.Thread.Sleep(1000); MessageBox.Show("Test.."); }); t.Start(
public void buttonAnswer_Click(object sender, RoutedEventArgs e)
{
Task t = new Task(() =>
{
System.Threading.Thread.Sleep(1000);
MessageBox.Show("Test..");
});
t.Start();
}
但当在设备上运行应用程序时,我在MessageBox.Show(“Test..”)上得到unauthorizedAccessExeption代码>行
您无法访问后台线程中的用户界面元素。您应该将调用封送到UI线程
使用async/await做这件事相当简单
public async void buttonAnswer_Click(object sender, RoutedEventArgs e)
{
await Task.Run(() =>
{
//Your heavy processing here. Runs in threadpool thread
});
MessageBox.Show("Test..");//This runs in UI thread.
}
如果不能使用async/await,可以使用Dispatcher.Invoke
/Dispatcher.BeginInvoke
方法在UI线程中执行代码。@Michael comment解决方案:
public void buttonAnswer_Click(object sender, RoutedEventArgs e)
{
var syncContext = TaskScheduler.FromCurrentSynchronizationContext();
Task t = new Task(() =>
{
System.Threading.Thread.Sleep(1000);
MessageBox.Show("Test..");
});
t.Start(syncContext);
}
在click handler methodvar syncContext=TaskScheduler.FromCurrentSynchronizationContext()的开头添加此行代码>。启动任务t
通过传递同步上下文-t.Start(syncContext)
@Michael,这将使线程在UI线程中运行。Sleep
这是一件不好的事情。@Michael谢谢你)这真的很有效@奈德,我不建议你这么做。如果您选择它,那么您正在UI线程中执行任务。这意味着Thread.Sleep
或任何处理代码也将在UI线程中运行,从而冻结UI。