Search code examples
c#windows-phone-8windows-phone

Windows Phone UnautorizedAccessExeption when using Task


I try using Task object to run code asynchronously:

public void buttonAnswer_Click(object sender, RoutedEventArgs e)
    {
        Task t = new Task(() =>
        {
            System.Threading.Thread.Sleep(1000);
            MessageBox.Show("Test..");
        });

        t.Start();
    }

But when run application on device i get UnautorizedAccessExeption exeption on MessageBox.Show("Test.."); line.

visual studio screenshot


Solution

  • You can't access the user interface elements in background thread. You should marshal the call to the UI thread instead.

    Using async/await it's fairly simple thing to do.

    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.
    }
    

    If you can't use async/await, you can use Dispatcher.Invoke/Dispatcher.BeginInvoke methods to execute the code in UI thread.