多个背景工作者+ C#

时间:2011-01-27 16:14:10

标签: c# multithreading backgroundworker

快速提问 - 是否可以同时运行两名后台工作人员?我似乎记得尝试过这一次并得到一个错误,并且似乎还记得读到你只能有一个......我找不到另一个线索,它谈到明确地有一个以上......

非常感谢任何想法!

干杯

1 个答案:

答案 0 :(得分:18)

您可以拥有尽可能多的后台工作人员并同时运行。例如:

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();