快速提问-是否可以让两个后台 worker 同时运行?我似乎记得曾经尝试过一次并遇到错误,并且似乎还记得读到您只能拥有一个……我找不到另一个讨论明确拥有多个的线程。
任何想法都非常感谢!
干杯
最佳答案
您可以根据需要拥有任意数量的后台 worker ,这些 worker 可以同时运行。例子:
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();
关于c# - 多个背景工+ C#,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4818809/