Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

BackgroundWorker Helper using Lambda Expressions

0.00/5 (No votes)
8 Jun 2012 1  
You can implement BackgroundWorker using Lambdas without any sort of helper class very easily.

Introduction

I have found that using Lambda Expressions with the BackgroundWorker makes maintenance much easier since you can have everything together in a single method. You can implement the BackgroundWorker using Lambdas without any sort of helper class very easily:

using (var backgroundWorker = new BackgroundWorker())
{
    Debug.Print(string.Format("Start BackgroundWorker {0}", 
         sw.ElapsedMilliseconds));
    backgroundWorker.DoWork += (s, e) =>
        {
          var baskets = FoxDataAccess.GetOrderBaskets().
            Select(i => new StaggedBlotterOrderBasketViewModel(i));
          var mainList = new ObservableCollection
            <StaggedBlotterOrderBasketViewModel>(baskets);
          e.Result = mainList;
        };
    backgroundWorker.RunWorkerCompleted += (s, e) =>
        {
          Debug.Print(string.Format("Completed BackgroundWorker {0}", 
            sw.ElapsedMilliseconds));
          _mainList = (ObservableCollection
            <StaggedBlotterOrderBasketViewModel>)e.Result;
          RaisePropertyChanged("MainListSource");
          Debug.Print(string.Format("Converted Basket Data {0}", 
            sw.ElapsedMilliseconds));
          IsBusy = false;
        };
    backgroundWorker.RunWorkerAsync();

However, using a helper can slightly reduce the code and do exactly the same thing:

BackgroundWorkerHelper.Run(
        (s, e) =>
            {
              var baskets = FoxDataAccess.GetOrderBaskets().Select(i => 
                new StaggedBlotterOrderBasketViewModel(i));
              var mainList = new ObservableCollection
                <StaggedBlotterOrderBasketViewModel>(baskets);
              e.Result = mainList;
            },
        (s, e) =>
            {
              Debug.Print(string.Format("Completed BackgroundWorker {0}", 
                sw.ElapsedMilliseconds));
              _mainList = (ObservableCollection
                <StaggedBlotterOrderBasketViewModel>)e.Result;
              RaisePropertyChanged("MainListSource");
              Debug.Print(string.Format("Converted Basket Data {0}", 
                sw.ElapsedMilliseconds));
              IsBusy = false;
            });

I think what I like about using this helper class the best is it looks a lot cleaner than working directly with the BackgroundWorker class. The helper is actually quite simple, and actually also handles ProgressChanged:

public static class BackgroundWorkerHelper
{
    public static void Run(DoWorkEventHandler doWork, 
              RunWorkerCompletedEventHandler completed = null, 
              ProgressChangedEventHandler progressChanged = null)
    {
      using (var backgroundWorker = new BackgroundWorker())
      {
        backgroundWorker.DoWork += doWork;
        if (completed != null)
          backgroundWorker.RunWorkerCompleted += completed;
        if (progressChanged != null)
        {
          backgroundWorker.WorkerReportsProgress = true;
          backgroundWorker.ProgressChanged += progressChanged;
        }
        backgroundWorker.RunWorkerAsync();
      }
    }
}

If you also have a ProgressChanged argument, there is the additional advantage of not only removing some boilerplate for the ProgressChanged event handler, but it also automatically sets the WorkerReportsProgress to true.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here