Skip to content

Goodbye BackgroundWorker Hello Tasks

June 9, 2014

So after years of using BackgroundWorkers to properly multi-thread long running operations and not lock up the UI, it is time to go another way and utilize Tasks.  I know this is a bit late but better than never right?  This method also allows for using a different way communicate with the GUI thread for updating progress bars or labels with status messages.  The Progress class is a nice addition and better performing than invoking on controls.


Progress<string> prog = new Progress<string>();

prog.ProgressChanged += (a, b) => { lblStatus.Text = b; };

Task<string>.Factory.StartNew(() =>


IProgress<string> pro = prog;

pro.Report(“Reporting Something”);

return “Done”;

}).ContinueWith(a =>


lblStatus.Text = a.Result;

}, TaskScheduler.FromCurrentSynchronizationContext());


The continue with is important because  if you put code under the full block it would get executed at the same time the task is running in the background.  So we do what we want in the ContinueWith so that it happens in the correct order and we use the TaskScheduler.FromCurrentSynchronizatoinContext to ensure that what happens there, happens on the GUI thread.

No comments yet

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: