TaskHelper class

Functions to start tasks in the background and synchronise them with the UI thread, as well as to wait for the WPF dispatcher.

For quickly starting off an activity in a background thread, there is the Task class from the Task Parallel Library in .NET 4.0. But this simple scenario is just the beginning. As soon as the background activity must be synchronised with the UI thread afterwards to display its result there, it’s getting complicated. This frequent case in GUI applications, and some other synchronisation tasks around the WPF dispatcher, are provided by this TaskHelper class.

Some of this can also be written with the C# 5.0 keywords async and await (.NET 4.5, VS 2012). This class was already written for .NET 4.0 applications and reduces the syntactic work to a minimum there.

Compatibility: .NET Version 4.0 or newer

Example

The following sample code shows the diverse usages of TaskHelper:

// Execute task in a background thread, then continue with code in the UI thread:
// Create (not display) an activity dialog
var dlg = new ActivityDialog("Please wait while the files are searched.");
var list = new List<string>();
var cts = TaskHelper.Start(
    c =>   // [CancellationToken]
    {
        // This code runs in a worker thread
        foreach (string item in HeavilySearchThings())
        {
            list.Add(item);
            // Check whether it should be aborted
            if (c.IsCancellationRequested)
            {
                return;
            }
        }
    },
    t =>   // [Task]
    {
        // This code runs in the UI thread afterwards
        // Close the dialog, we don't need it anymore
        dlg.Finish();
        if (t.IsCanceled)
        {
            // The background thread was cancelled
            App.InformationMessage("The search was cancelled.");
        }
        else if (t.Exception != null)
        {
            // In the background thread, an unhandled exception occured
            App.ErrorMessage("That didn’t work.", t.Exception);
        }
        else
        {
            // All fine, the result can now be presented
            PublicList = list;
        }
    });
// Meanwhile, show an activity dialog with a Cancel button
if (dlg.ShowDialog() == false)
{
    // Cancel the background activity if the dialog was dismissed by the user
    cts.Cancel();   // [CancellationTokenSource]
}

// Process other GUI events before continuing here (blocks):
TaskHelper.DoEvents();

// Process other GUI events down until a certain DispatcherPriority (blocks):
TaskHelper.DoEvents(DispatcherPriority.DataBind);

// Execute a task after other events down until the Loaded priority are finished:
TaskHelper.WhenLoaded(() => SelectItemFromList());

// Execute a task after all other events are finished:
TaskHelper.Background(() => SelectItemFromList());

Download

TaskHelper.cs5.6 KiBSource code of the TaskHelper class

Changes

2015Aug27
Added the AppDispatch method for easy WPF application dispatching.

Licence and terms of use

Copying and distribution of this file, with or without modification, are permitted provided the copyright notice and this notice are preserved. This file is offered as-is, without any warranty. (GNU All-Permissive licence)

Statistic data

  • Created on 2012-09-12, updated on 2015-08-27.