Click here to Skip to main content
Click here to Skip to main content

BackgroundWorker Helper using Lambda Expressions

, 8 Jun 2012
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Clifford Nelson
Software Developer (Senior) ETeam/Delloitte
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 three years has been working primarily as a senior WPF/C# and Silverlight/C# developer. Currently working as WPF developer with NBC Universal in Universal City, CA

Comments and Discussions

 
QuestionAny similar code available for VB.NET? PinmemberMember 822438220-Mar-14 5:07 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140721.1 | Last Updated 8 Jun 2012
Article Copyright 2012 by Clifford Nelson
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid