1

I have a background progress (factory) which creates more background processes (workers) to split up the work load. I need each worker to report it's progress to the factory and the factory to report it to the GUI. For the factory I can use

Factory.ReportProgress(value);

But I can't seem to refer to my workers from inside the DoWork method. My factory DoWork:

private void Factory_DoWork(object sender, DoWorkEventArgs e)
{            
    BackgroundWorker[] Workers = new BackgroundWorker[ThreadCount];

    for (int i = 0; i < ThreadCount; i++)
    {
        BackgroundWorker Worker = new BackgroundWorker();

        Worker.WorkerReportsProgress = true;
        Worker.WorkerSupportsCancellation = true;

        Workers[i] = Worker;

        Worker.DoWork += Worker_DoWork;
        Worker.RunWorkerCompleted += Worker_RunWorkerCompleted;
        Worker.ProgressChanged += Worker_ProgressChanged;

        Worker.RunWorkerAsync(argument: TimesToRun);

        Progress++;
        Factory.ReportProgress(Progress);
    }
}

My Worker DoWork:

private void Worker_DoWork(object sender, DoWorkEventArgs e)
{

    for (int i = 0; i < (int)e.Argument; i++)
    {
        if (Running)
        {
            //Do work
            Thread.Sleep(10);                    
        }
    }
}

How do I make the worker report progress to the factory each time it completes 1 for loop?

elmer007
  • 1,412
  • 14
  • 27
Tomas
  • 181
  • 2
  • 10

1 Answers1

0

You can report progress by calling the ReportProgress method of the BackgroundWorker instance inside the DoWork method. The active BackgroundWorker instance is the object sender argument.

private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
    // Get the BackgroundWorker that raised this event.
    BackgroundWorker worker = sender as BackgroundWorker;

    for (int i = 0; i < (int)e.Argument; i++)
    {
        if (Running)
        {
            //Do work
            Thread.Sleep(10);  
            //Report Progress
            worker.ReportProgress(i);
        }
    }
}

See documentation on microsoft Website : BackgroundWorker DoWork Event