Building a Universal Windows App with Asynchronous Execution

The cornerstone consists of these 4 principles:

  1. Mark all of your methods that might “take a while” as async, which also means giving them a return type such as Task<string> when they return a string, or Task when they simply return control. Mark every method that calls such a method as async too, and await the asynchronous calls, all the way up the chain – in XAML you will no longer be able to use await, 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 any await statement. It completes the await statements in the order they appear, and the method returns control. Clever, right? 😀 Forget about Task<T>.Wait() and other Task methods – those do exactly the opposite and block your thread mercilessly!
  2. 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.
  3. Place the methods that update the UI in the Page that contains it. There you have access to the Dispatcher object. In WPF/WF this was also done through the Invoke method. Here it is better: you don’t have to create delegates and methods for them, you just wrap the call in Dispatcher.RunAsync
  4. 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 bool or an object is enough – and before displaying the final message, check, for example, the count or whether the values are equal.
  5. CSHARP
    async Task SetItemsToDownloadQueueListBox()
    {
        await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =&gt;
            {
                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.

Categories

Leave a Reply