C# – How to use BackGroundWorker in class file

backgroundworkercnet

My program.cs calls the mdi parent frmMain. frmMain then opens different child forms based on user action.

All the processing logic is written in BusinessLogic.cs. frmMain at load calls the methods of BusinessLogic.cs to initially populate the data. The child forms too call BusinessLogic to fetch data and process it. I'd like to do all this through a BackGroundWorker ie the frmMain calls the (say) StartBGWorker() method of BusinessLogic.cs and this method creates a backgroundworker for this specific call, calls the Do_work event, does the fetching & processing and closes when done.

I'm at a loss about how to create the instance and the events for backgroundworker. So how exactly do I use backgroundworker in a class file?

Edit: Maybe my logic is wrong and I should add a BGW to each form that calls BusinessLogig.cs. Then whenever I call a method of BusinessLogic I can do so through backgroundworker. Would this be a better implementation?

Edit2: Feel a bit idiotic about my doubt now that I found a way. I just created a public static method with the initialize code of BGW in BusinessLogic. Now whenever I need to do processing I first call this method from my forms.
I'd like to know if my implementation of BGW is standard or is there any way to improve the design.

Best Answer

Include:

using System.ComponentModel;

Define it in your class:

private BackgroundWorker BackgroundWorker = new BackgroundWorker();

Initialize it:

BackgroundWorker.WorkerSupportsCancellation = false;
BackgroundWorker.WorkerReportsProgress = true;
BackgroundWorker.DoWork += BackgroundWorker_DoWork;
BackgroundWorker.ProgressChanged += BackgroundWorker_ProgressChanged;
BackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler( BackgroundWorker_RunWorkerCompleted );

To start it:

BackgroundWorker.RunWorkerAsync();

The usage is exactly the same as you know from Windows Forms.