Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Backgroundworkers + C#

Quick question - is it possible to have two background workers running at once? I seem to remember trying this once and getting an error, and also seem to remember reading that you can only have one... I can't find another thread that talks about having more than one explicitly though..

Any thoughts are much appreciated!

Cheers

like image 781
keynesiancross Avatar asked Jan 27 '11 16:01

keynesiancross


1 Answers

You can have as many background workers as you like and running simultaneously. Example:

var worker1 = new BackgroundWorker { WorkerReportsProgress = true };
var worker2 = new BackgroundWorker { WorkerReportsProgress = true };
DoWorkEventHandler doWork = (sender, e) =>
{
    for (int i = 0; i < 10; i++)
    {
        var progress = (int)((i + 1) * 100.0 / 10);
        var worker = (BackgroundWorker)sender;
        worker.ReportProgress(progress);
        Thread.Sleep(500);
    }
};
worker1.DoWork += doWork;
worker2.DoWork += doWork;
worker1.ProgressChanged += (sender, e) =>
{
    label1.Text = e.ProgressPercentage.ToString();
};
worker2.ProgressChanged += (sender, e) =>
{
    label2.Text = e.ProgressPercentage.ToString();
};

worker1.RunWorkerAsync();
Thread.Sleep(1000);
worker2.RunWorkerAsync();
like image 54
Darin Dimitrov Avatar answered Oct 04 '22 15:10

Darin Dimitrov