Click here to Skip to main content
15,867,308 members
Articles / Programming Languages / C#
Tip/Trick

BackgroundWorker Helper using Lambda Expressions

Rate me:
Please Sign up or sign in to vote.
5.00/5 (9 votes)
8 Jun 2012CPOL 16.2K   272   13   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:

C#
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:

C#
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:

C#
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Clifford Nelson Consulting
United States United States
Has been working as a C# developer on contract for the last several years, including 3 years at Microsoft. Previously worked with Visual Basic and Microsoft Access VBA, and have developed code for Word, Excel and Outlook. Started working with WPF in 2007 when part of the Microsoft WPF team. For the last eight years has been working primarily as a senior WPF/C# and Silverlight/C# developer. Currently working as WPF developer with BioNano Genomics in San Diego, CA redesigning their UI for their camera system. he can be reached at qck1@hotmail.com.

Comments and Discussions

 
QuestionAny similar code available for VB.NET? Pin
Member 822438220-Mar-14 5:07
Member 822438220-Mar-14 5:07 
I am trying to use a lambda expression with the backgroundworker class in VB.NET. Any similar code available for VB.NET?

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.