I am trying to use message dialog in dispatch timer to alter user when the time is complete. but at times it gives following error: "Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))". How to resolve this?
Code:
public DetailPage()
{
timer = new DispatcherTimer();
timer.Tick += dispatcherTimer_Tick;
timer.Interval = new TimeSpan(0, 0, 1);
this.txtTimer.Text = GlobalVariables.totalTime.Minutes + ":" + GlobalVariables.totalTime.Seconds + "mins";
timer.Start();
}
async void dispatcherTimer_Tick(object sender, object e)
{
if (GlobalVariables.totalTime.Minutes > 0 || GlobalVariables.totalTime.Seconds > 0)
{
GlobalVariables.totalTime = GlobalVariables.totalTime.Subtract(new TimeSpan(0, 0, 1));
this.txtTimer.Text = GlobalVariables.totalTime.Minutes + ":" + GlobalVariables.totalTime.Seconds + " mins";
}
else
{
timer.Tick -= dispatcherTimer_Tick;
timer.Stop();
MessageDialog signInDialog = new MessageDialog("Time UP.", "Session Expired");
// Add commands and set their callbacks
signInDialog.Commands.Add(new UICommand("OK", (command) =>
{
this.Frame.Navigate(typeof(HomePage), "AllGroups");
}));
// Set the command that will be invoked by default
signInDialog.DefaultCommandIndex = 1;
// Show the message dialog
await signInDialog.ShowAsync();
}
}
I am getting the error at:
// Show the message dialog
await signInDialog.ShowAsync();
Like Jeff says, the timer Tick event handler code is running on a different thread than the UI thread. You'll have to get back to this UI thread to manipulate anything in the UI: message dialog, changing properties, etc.
Note that I do stop the timer in the event handler. If you don't close a message dialog in time before another one is shown, you'll get an access denied on the 2nd ShowAsync too (because the first is still open).
The
dispatcherTimer_Tick
method is running on a different thread than the UI. If you want to access stuff that is bound to the UI thread, like UX, you must get back onto the UI thread. Easiest way to do this is wrap your code with