I am developing a windows store 8.1 app using C# and xaml. When i tried to update the UI from code behind file i got an exception which is
" the application called an interface that was marshalled for a different thread"
i have added the below code to update the UI
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
statustextblk.Text = "Offline sync in progress...";
}
);
This is working fine. But i want to update the same textblack after offline sync is completed. So for this i wrote the below code, the code looks like this
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
statustextblk.Text = "Offline sync in progress...";
}
);
await SharedContext.Context.OfflineStore.ScheduleFlushQueuedRequestsAsync();
Debug.WriteLine("Refresh started");
if (SharedContext.Context.OfflineStore != null && SharedContext.Context.OfflineStore.Open)
await SharedContext.Context.OfflineStore.ScheduleRefreshAsync();
RefreshSuccess = true;
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
statustextblk.Text = "Offline sync completed...";
Task.Delay(1000);
statustextblk.Text = "";
}
);
But it is not displaying the "Offline sync completed..." message in the UI.
How can i show it in the UI once the method is executed?
Can someone please help me out?
Thanks in advance
If you comment Task.Delay(1000), "Offline sync completed..." will show within a very short time but will disappear immediately because you set the statustextblk.Text = "".
Therefore you can refer to @Raymond said in the comment. Add modifier ‘async’ before () => and modifier ‘await’ before Task.Delay(1000); You can refer to the demo I made as following:
private async void Button_Click(object sender, RoutedEventArgs e)
{
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
statustextblk.Text = "Offline sync in progress...";
}
);
Debug.WriteLine("Refresh started");
await Task.Delay(1000);
//RefreshSuccess = true;
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
async () =>
{
statustextblk.Text = "Offline sync completed...";
await Task.Delay(1000);
statustextblk.Text = "";
}
);
}