Reputation: 41
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.
Upvotes: 0
Views: 36
Reputation: 41
@Michael comment solution:
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);
}
Upvotes: 0
Reputation: 73472
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.
Upvotes: 1