I am new to C# development and wish to create a more responsive UI. In my preliminary research, I have seen two methods for achieving this:
- Multi-threading in conjunction with the BackgroundWorker class.
- The newer Async/Await modifiers.
Does newer mean better? What’s the difference between the two methods? If I wish to create a new project, how do I choose which method to go with?
EDIT: Maybe I should specify. I am creating a Windows Forms application, where all necessary data will be saved/loaded on the local disk. I will also be communicating with several USB devices.
1
You will be able to accomplish your task using BackgroundWorker
. It is a well known class, and many people have used it.
The new C# 5 async
and await
keywords basically just make it easier to write readable asynchronous code. There may be fewer tutorials and examples of how to accomplish various tasks with these keywords rather than BackgroundWorker
.
Unless you need to use an older version of C#, I suggest learning how to use async
and await
.
The async
and await
keywords will not make your application more responsive on their own. They simply make the calling and handling of methods that return Task
objects more convenient. In order to make async
/await
actually use background threads, you will need to combine with the usage of things like:
Task.Start()
– Starts a given task using theTaskScheduler
.- PLINQ – Execute a series of operations in parallel, returns a Task.
TaskCompletionSource
– A custom way to handle async tasks. One place I used this was to handle events coming from aWebBrowser
control.- Other
async
methods, such as many of the functions in the Win 8 API.
In other words, async
/await
is an extension of the Task-Based Asynchronous Pattern. You can find a large host of information, including many samples, here.
The BackgroundWorker
is a WinForms component that creates 1 background thread using the Event-Based Asynchronous pattern, and you can populate the work done on this background thread with your own code in the DoWork
event handler. In general, Microsoft no longer recommends using this pattern (see the bottom of the page here), though if you are familiar with it already it may still be a simple option.
Another option not mentioned, is the Reactive Extensions for .NET. This is another great framework for adding responsiveness to your apps.
5
I’d say that async
–await
is much more flexible than BackgroundWorker
. And if you want to do something that fits BackgroundWorker
, you can do it with async
–await
too, with more readable and more type-safe code.
Because of that, I think you should prefer using async
–await
over BackgroundWorker
.