Keith Clark Keith Clark - 4 years ago 162
C# Question

Check if a Winforms BackgroundWorker is active upon opening a form

I currently have a

form that contains a
object. In the left panel, I have several buttons that when clicked, will open a specific form in the right panel.

One of these forms,
, has a
) that does a lot of database table maintenance and building of data tables in the database for reporting purposes. While this
is running, I can navigate to any other form simply by clicking the appropriate button in the left panel of the
form. When the
is done, it displays a
, no matter where I am in the application.

What I am trying to accomplish is to check if the
is running when I load the
form. I tried

if (bgLaborForecast.IsBusy) {

But when I enter the form, the
status is always false.

How can I check for the process being active when I load the form?

Answer Source

You need to do interface

public interface IState
    bool BgWorkerIsWorking { get; set; }

then implement it in Form1:

public partial class Form1 : Form, IState
private bool _working;
public bool BgWorkerIsWorking
    get { return _working; }
    set { _working = value; }

In MainForm declare variable to keep form

Form firstForm;

And in button this

if (first == null)// If form wasn't created
    first = new Form2();// Create form and show
else// If form was created
    var check = first as IState;// Use form as our interface
    if (check.BgWorkerIsWorking)// And check state
        // Here you do something.

And at last in Form1 in BgWorker events you do this

private void Bg_DoWork(object sender, DoWorkEventArgs e)
    _working = true;
    // Here is your code
private void Bg_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    _working = false;

Ofcourse your worker initialization must be this

using (BackgroundWorker bg = new BackgroundWorker())
    bg.DoWork += Bg_DoWork;
    bg.RunWorkerCompleted += Bg_RunWorkerCompleted;

And just in case, worker start work after


P.S. This steps must be repeated for each form you create. declare secondForm, thirdForm and so on.
P.P.S. You can design more complicated algorithm, store created forms in array, add extra fields in interface and so on. This example show basic principle :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download