How to Replace BackgroundWorker with Async/Await and Tasks
BackgroundWorker was introduced early in .NET Framework as an easy way to do asynchronous tasks in Windows Forms applications. Though it is WinForms centric and not considered part of the async patterns, its beauty lies in the simplicity and just enough encapsulation. You don’t need to know much about the async patterns to use this tiny little class in your code base, and things often just work.
Different async patterns were developed by Microsoft to assist developers.
However, after .NET Framework 4.x came with
Task based classes (Task Parallel Library), and especially 4.5 where
await was introduced, you should move away from
BackgroundWorker whenever possible.
Well, the only challenge is, how we can convert the code base from
await, which I will show you in this post.
The Sample Project in Initial State
The project is hosted on GitHub, and is Windows Forms based.
To make full use of
BackgroundWorker’s capability, both progress reporting and cancellation are utilized. As you can see it is rather simple, and easy to understand.
This pattern does have its problems, like
- You need to keep in mind that
DoWorkevent handler runs by a separate thread, not the UI thread (aka main thread), though that’s not quite obvious from the code.
RunWorkerCompletedevent handlers, however, are executed by the UI thread. That’s why there the text of label can be updated directly.
- Cancellation required several pieces to be set, and if you miss one piece the result won’t meet your expectation.
Thread.Sleepis used to mimic a slow sync function call (usually in your own project here should be slow function calls like
When you need to call an async function like
SqlCommand.ExecuteScalarAsync, it is not obvious how to write the correct code inside
DoWork. This is a bigger issue with new .NET APIs, as they are full of async functions (SignalR for example).
Well, now it’s time to kill the bird. And you can easily see the changes here in the commit.
Obvious parts are,
CancellationTokenare needed now to implement cancellation.
- There is no need to have separate methods and everything can come together in a single method.
- Most importantly the heavy task must be in a
Taskobject now, and here I use
Task.Delayas an example (again in your project things like
SqlCommand.ExecuteScalarAsyncshould be here).
You must keep in mind there are many important tips on proper usage of
await, including but not limited to
async voidis only used for the button click event handler as Microsoft documented.
- While the heavy task is executed in the background (and awaited), changing the text of label is in UI thread, as after the
awaitline the execution context is restored.
Capturing/restoring such context is expensive, so you should suppress that with
ConfigureAwait(false)if you don’t need the context. Microsoft guys wrote a must-read post here.
await have been very important addition to .NET ecosystem, so use them whenever possible and that’s going to make your life a lot easier.