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
.