6

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

1 Answer 1

18

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(); 
Sign up to request clarification or add additional context in comments.

2 Comments

Why not create separate doWork delegates for worker1 and worker2?
For the sake of example it wasn't necessary.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.