我读到了使用BackgroundWorker类在Windows窗体应用程序中实现线程。我有一个小问题:如果我想同时运行5个线程来处理指定的任务,我必须创建5个BackgroundWorker控件或只需要一个?
如果你只是在谈论BackgroundWorker
,那么你必须创建5个背景工作者。如果你只想要5个线程,你可以自己创建。然后问题变成如何将进度和完成传回UI线程。使用BackgroundWorker
,您可以使用WorkerReportsProgress
/ ReportProgress
和Completed事件。现在,您可以确定只使用BackgroundWorker
DoWork
处理程序来生成您想要的线程,并通过ReportProgress
和Completed
管理从这些线程返回UI线程的数据通信。
例如:
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
Thread thread1 = new Thread(ThreadOneEntry);
thread1.Start();
Thread thread2 = new Thread(ThreadTwoEntry);
thread2.Start();
Thread thread3 = new Thread(ThreadThreeEntry);
thread3.Start();
Thread thread4 = new Thread(ThreadFourEntry);
thread4.Start();
Thread thread5 = new Thread(ThreadFiveEntry);
thread5.Start();
thread1.Join();
thread2.Join();
thread3.Join();
thread4.Join();
thread5.Join();
// do something to report results from threads1-5
}
当然,这对进展没有任何作用 - 这将是非常具体的应用程序,我想出的任何东西都可能与你的工作完全不同,没有任何帮助。但是,每个线程可以直接通过BackgroundWorker.ReportProgress
方法报告进度 - 您只需要为每个线程提供BackgroundWorker
实例或ReportProgress
方法的委托。
对于后台工作程序来说,它也不是非常有效地使用线程,它只是进入等待其他线程的等待状态,DoWork
事件处理程序可以轻松地执行其他线程条目之一所具有的一些工作。 ..
如果您使用的是.NET 3.5或更高版本,并且您希望执行具有结果的后台工作,我建议使用Task<T>
而不是Thread
。另外,启动自己的线程不会产生负载平衡。通过TPL的任务自己负载平衡......
BackgroundWorker基本上是一个单独的线程,因此如果需要运行多个线程,则需要多个实例。