Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/opengl/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用任务时Windows Phone UnauthorizedAccessExection_C#_Windows Phone 8_Windows Phone - Fatal编程技术网

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 method
var syncContext=TaskScheduler.FromCurrentSynchronizationContext()的开头添加此行。启动任务
t
通过传递同步上下文-
t.Start(syncContext)
@Michael,这将使
线程在UI线程中运行。Sleep
这是一件不好的事情。@Michael谢谢你)这真的很有效@奈德,我不建议你这么做。如果您选择它,那么您正在UI线程中执行任务。这意味着
Thread.Sleep
或任何处理代码也将在UI线程中运行,从而冻结UI。