The cornerstone consists of these 4 principles:
- Mark all of your methods that might “take a while” as
async, which also means giving them a return type such asTask<string>when they return a string, orTaskwhen they simply return control. Mark every method that calls such a method asasynctoo, andawaitthe asynchronous calls, all the way up the chain – in XAML you will no longer be able to useawait, that is the top level.
This signals that you want the method to run asynchronously. It works like this: the program starts executing the code that does not depend on anyawaitstatement. It completes theawaitstatements in the order they appear, and the method returns control. Clever, right? 😀 Forget aboutTask<T>.Wait()and otherTaskmethods – those do exactly the opposite and block your thread mercilessly! - Point 1 also applies to event handlers (such as a button click) – they are the ones that will always trigger further operations. A constructor cannot be
async. - Place the methods that update the UI in the
Pagethat contains it. There you have access to theDispatcherobject. In WPF/WF this was also done through theInvokemethod. Here it is better: you don’t have to create delegates and methods for them, you just wrap the call inDispatcher.RunAsync - If you want to run something in a loop whose worker thread doesn’t return any value and then display a status saying everything succeeded, it probably won’t work. At least it didn’t work for me. The thread method needs to return something – a
boolor anobjectis enough – and before displaying the final message, check, for example, the count or whether the values are equal.
CSHARP
async Task SetItemsToDownloadQueueListBox()
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
downloadQueueListBox.ItemsSource = null;
downloadQueueListBox.ItemsSource = VideosInListBox.videos;
}
);
}I also struggled quite a bit with this one. Who would have guessed that if I want to update the items in a ListBox that are displayed using a XAML DataTemplate, I first have to set the ItemsSource property to null and then set it to the collection again. While I was testing it, it worked absolutely reliably, with no errors caused by one piece of code getting ahead of another.