Universal Windows Apps with XAML and C# Unleashed: Threading, Windows, and Pages
- Understanding the Threading Model for Universal Apps
- Displaying Multiple Windows
- Navigating Between Pages
- Summary
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.
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 =new
MessageDialog
("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:
async
Task
ShowDialog() {MessageDialog
dialog =new
MessageDialog
("Title"
);IUICommand
command =dialog.ShowAsync();
await
// 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:
async
Task
ShowDialog() {MessageDialog
dialog =new
MessageDialog
("Title"
);IAsyncOperation
<IUICommand
> operation = dialog.ShowAsync();IUICommand
command =operation;
await
// 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.
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:
// A handler for MediaCapture's Failed event
void
Capture_Failed(MediaCapture
sender,MediaCaptureFailedEventArgs
e) {// This throws an exception:
this
.textBlock.Text ="Failure capturing video."
; }
The exception thrown explains, “The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD)).”
With DependencyObject’s Dispatcher property of type CoreDispatcher, however, you can marshal a call back to the proper UI thread needed to update the TextBlock. It can be used as follows:
// A handler for MediaCapture's Failed event
async
void
Capture_Failed(MediaCapture
sender,MediaCaptureFailedEventArgs
e) {
await this
.Dispatcher.RunAsync(CoreDispatcherPriority
.Normal, () =>{
// This now works, because it's running on the UI thread:
this
.textBlock.Text ="Failure capturing video."
;});
}
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.