This chapter from Universal Windows Apps with XAML and C# Unleashed begins by examining a very important topic, although one that many developers take for granted: the threading model for universal apps. This background is especially helpful for the advanced feature of writing an app that displays multiple windows, which is the second topic in this chapter. The third and final topic—navigating between a window’s pages—is a feature leveraged by just about every real-world app.

This chapter is from the book

This chapter is from the book

Understanding the Threading Model for Universal Apps

Universal apps have two types of threads that can run your code: UI threads and background threads. (Other types of threads exist, but they are implementation details.) As much as possible, a UI thread should be kept free to process input and update UI elements. Therefore, long-running work should always be scheduled on a background thread.

Typically, an app has a single UI thread, but that’s only because an app typically has a single window. Each window has its own UI thread, so an app with multiple windows (covered in the upcoming “Displaying Multiple Windows” section) has multiple UI threads.

If you have a long-running computation to perform, which therefore isn’t appropriate for a UI thread, you don’t get to explicitly create a background thread for the task. Instead, you schedule it via a static RunAsync method on the Windows.System.Threading.ThreadPool class. Windows manages all background threads for you.

There is always a main UI thread, even if the corresponding main window has not yet been shown. For example, if an app is activated via a contract such as the File Picker contract (see Chapter 21, “Leveraging Contracts”), the app typically displays a special file-picking window and never displays its main window. Yet the app has two UI threads running in this scenario, so your code can always count on global state created by the main thread.

UI objects must be created and called on a UI thread. This includes every class deriving from DependencyObject, which is most classes in the XAML UI Framework. Outside of the XAML UI Framework, most Windows Runtime objects can be created and used on any thread, and you control their lifetime. This makes them very natural to use in C# without worrying about threading or COM-style apartments. Such objects are called agile objects.

ASTA Threads

In documentation and error messages, UI threads are sometimes referred to as ASTA threads. ASTA stands for App Single-Threaded Apartment, which is a nod to COM’s notion of single-threaded apartments (STA).

ASTA threads are similar to COM’s STA threads in that they provide an easy-to-program, single-threaded experience. But they have an enhancement that COM’s STA threads do not: they are not reentrant, unless the incoming call is logically connected to the one in progress. In other words, if you make a call from a UI thread to another thread (or process), and that thread needs to call back to the UI thread, the Windows Runtime does a lot of work to track this and allow it. On the other hand, arbitrary code is prevented from calling into the UI thread while it is doing work. This prevents a huge class of bugs that plague traditional desktop apps, and means that UI objects generally don’t need locking to protect themselves. The Windows Runtime also prevents UI threads from calling each other directly, as that would be prone to deadlock.

Awaiting an Asynchronous Operation

Windows Runtime APIs are designed to make it really hard to block a UI thread. Whenever the Windows Runtime exposes a potentially-long-running operation, it does so with an asynchronous method that performs its work on a background thread. You can easily identify such methods by their Async suffix. And they are everywhere. For example, showing a MessageDialog (discussed in Chapter 14, “Other Controls”) requires a call to ShowAsync:

MessageDialog dialog = newMessageDialog("Title");
IAsyncOperation<IUICommand> operation = dialog.ShowAsync();
// The next line of code runs in parallel with ShowAsync's background work
MoreCode();

Asynchronous methods in the Windows Runtime return one of several interfaces such as IAsyncOperation or IAsyncAction. Asynchronous methods in .NET return a Task. These are two different abstractions for the same set of asynchronous patterns. The System.WindowsRuntimeSystemExtensions class provides several AsTask extension methods for converting one of these interfaces to a Task, as well as AsAsyncOperation and AsAsyncAction extension methods for converting in the opposite direction.

In the preceding code snippet, when ShowAsync is called in this manner, the call returns immediately. The next line of code can run in parallel with the work being done by MessageDialog on a different thread. When ShowAsync’s work is done (because the user dismissed the dialog or clicked one of its buttons), MessageDialog communicates what happened with an IUICommand instance. To get this result, the preceding code must set operation’s Completed property to a delegate that gets called when the task has finished. This handler can then call operation’s GetResults method to retrieve the IUICommand.

Of course, such code is pretty cumbersome to write, and the proliferation of asynchronous methods would result in an explosion of such code if it weren’t for the C# await language feature. When a method returns one of the IAsyncXXX interfaces or a Task, C# enables you to hide the complexity of waiting for the task’s completion. For the ShowAsync example, the resulting code can look like the following:

asyncTask ShowDialog()
{
MessageDialog dialog = newMessageDialog("Title");
IUICommand command = await dialog.ShowAsync();
// The next line of code does not run until ShowAsync is completely done
MoreCodeThatCanUseTheCommand(command);
}

When the ShowAsync call is made in this manner, the current method’s execution stops—without blocking the current thread—and then resumes once the task has completed. This enables the code to retrieve the IUICommand object as if ShowAsync had synchronously returned it, rather than having to retrieve it from an intermediate object in a convoluted fashion. You can only use the await keyword in a method that is marked with an async keyword. The async designation triggers the C# compiler to rewrite the method’s implementation as a state machine, which is necessary for providing the handy await illusion.

People commonly refer to this pattern as “awaiting a method,” but you’re actually awaiting the returned IAsyncXXX or Task object. As before, the method actually returns promptly. This is clearer if the preceding code is expanded to the following equivalent code:

asyncTask ShowDialog()
{
MessageDialog dialog = newMessageDialog("Title");
IAsyncOperation<IUICommand> operation = dialog.ShowAsync();
IUICommand command = await operation;
// The next line of code does not run until the operation is done
MoreCodeThatCanUseTheCommand(command);
}

It’s also worth noting that the async designation does not appear in the metadata for a method when it is compiled. It is purely an implementation detail. Again, you’re not awaiting a method; it simply happens to return a data type that supports being awaited.

Notice that the sample ShowDialog method returns a Task, which seems wrong because the method does not appear to return anything. However, the async-triggered rewriting done by the C# compiler does indeed return a Task object. This enables an asynchronous operation to be chained from one caller to the next. Because ShowDialog returns a Task, its caller could choose to await it.

If an async method actually returns something in its visible source code, such as the command object in the preceding code, then it must return Task<T>, where T is the type of the object being returned. In this example, it would be Task<IUICommand>. The C# compiler enforces that an async method must either return Task, Task<T>, or void. This means that ShowDialog could be rewritten with async void instead of async Task and it would still compile. You should avoid this, however, because it breaks the composition of asynchronous tasks.

Avoid defining an async method with a void return type!

If you do this, your callers cannot await or otherwise leverage an operation returned by your method (because it doesn’t return anything), which makes it harder for their code to behave correctly. This cannot be avoided, however, on methods that must match a delegate signature, such as a Button’s Click handler.

Do not use Task.Wait!

The .NET Task object provides many useful abstractions for cancellation and advanced control flow. You can also schedule your own long-running task via Task.Run, which directly returns a Task, rather than using ThreadPool.RunAsync, which returns an IAsyncAction instead. (Task.Run should really be called Task.RunAsync.)

One feature that you should avoid is Task’s Wait method. Although Waiting for a task to complete sounds similar to awaiting the task to complete, the Wait method blocks the current thread. Besides defeating the purpose of the background work, for cases such as showing a MessageDialog, this causes a deadlock:

You can leverage the nice await control flow for APIs that don’t return a Task or IAsyncXXX by wrapping the use of the APIs with an object called TaskCompletionSource. This has a Task property that you can return to your callers, and methods that you can call at the appropriate time to signal that the Task has completed, failed, or been canceled. TaskCompletionSource is used later in this chapter to provide a nice way to create and show additional windows.

Transitioning Between Threads

Occasions often arise when one thread needs to schedule work to be executed on another thread. For example, although events on XAML objects are raised on the same UI thread that created the object, this is usually not the case for non-UI objects in the Windows Runtime. Instead, they are raised on whatever background thread happens to be doing the work.

An example of this can be seen with the events defined by MediaCapture, a class described in Chapter 13, “Audio, Video, and Speech.” The following code incorrectly tries to update the UI to notify the user about a failure to capture video from the camera:

Here, an anonymous method is used for RunAsync’s second parameter (which must be a parameterless DispatchedHandler delegate) to keep the code as concise as possible. The code must be scheduled to run at one of the following priorities, from highest to lowest: High (which should never be used by app code), Normal, Low, and Idle (which waits until the destination thread is idle with no pending input).

This CoreDispatcher mechanism is also how one window can communicate with another window. Each Window, along with related Windows Runtime abstractions, expose a Dispatcher property that can schedule a delegate to run on its own UI thread.