Asynchronous Background Processing using .NET Tasks

A replacement for BackgroundWorker

In the past I've relied on the BackgroundWorker class being a very handy class to use for quick and dirty background processing.

On a recent project I however wasn't happy with the over all design of the background processing and wanted a cleaner and less error prone solution than the BackgroundWorker.

I had an issue with the multiple event handlers I needed to implement, the brittle hand-offs of data between starting/completing as the same changes needed to be made in multiple locations and the completion function inevitably had to know about the original parameters.

With a little help from some intelligent people on StackOverflow I came up with the abstract class AsyncBackgroundProcessor<T,R,N> that abstracts away all the boilerplate surrounding posting units of work on a background thread and retrieving them.

Features

  1. Leverages .NET Tasks and functors

  2. Automatically marshals between the background thread and the main UI thread

  3. Supports a Progress Event that is automatically raised on the main UI thread

  4. Utilizes generics/templating to strongly type input, output and progress events

How to use

Have a class that you intend to use to perform your background activity inherit from the AsyncBackgroundProcessor class and define the necessary generics types. This class then just needs to return the logic to run in the background as a functor from the CreateAsyncProcess abstract function.

The RunAsync and CancelAsync functions can then be called on your class to initiate or cancel the background progress.

More examples can be found in the Corrector and Analyser classes in the Rectify project.

The Code

Can be found on my public Gist and as a apart of my Rectify project on GitHub.

The code is also the core code embedded below



Software Developer
For hire


Developer & Programmer with +15 years professional experience building software.


Seeking WFH, remoting or freelance opportunities.