Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
2 contributors

Users who have contributed to this file

@KarlErickson @oldnewthing
57 lines (44 sloc) 2.1 KB

Update the UI thread from a background thread

Enables code running on a background thread to schedule work that will run on the UI thread.

Code running on a background thread cannot manipulate UI elements directly without raising a cross-thread exception. Instead, you must run UI code using a dispatcher. This task snippet encapsulates the typical dispatcher usage in Universal Windows Platform (UWP) apps.

using System;
using System.Threading.Tasks;
using Windows.ApplicationModel.Core;
using Windows.UI.Core;

public static async Task CallOnUiThreadAsync(CoreDispatcher dispatcher, DispatchedHandler handler) =>
    await dispatcher.RunAsync(CoreDispatcherPriority.Normal, handler);
    
public static async Task CallOnMainViewUiThreadAsync(DispatchedHandler handler) => 
    await CallOnUiThreadAsync(CoreApplication.MainView.CoreWindow.Dispatcher, handler);

Usage

// Single-view app can assume the UI thread is the main view (since there is only one).
private async void NetworkInformation_NetworkStatusChanged(object sender)
{
    await CallOnMainViewUiThreadAsync(() =>
    {
        // Update the UI to reflect the current network status. 
    });
}

// Multi-view app should use the dispatcher for the UI thread they want to run on.
private async void NetworkInformation_NetworkStatusChanged(object sender)
{
    await CallOnUiThreadAsync(this.Dispatcher, () =>
    {
        // Update this page's UI to reflect the current network status.
    }
}

See also

CoreDispatcher class
Lambda expressions (anonymous methods using the "=>" syntax)

The UWP Community Toolkit includes an extended version of this task snippet in the form of a DispatcherHelper class (source, docs).

You can’t perform that action at this time.