Windows Phone 使用 Task 时出现 UnautorizedAccessExeption

Windows Phone UnautorizedAccessExeption when using Task

我尝试使用 Task 对象 运行 异步编码:

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.."); 行得到 UnautorizedAccessExeption 异常。

visual studio screenshot

您无法在后台线程中访问用户界面元素。您应该改为将调用编组到 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评论解:

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