如果主要后台工作者在一种方法中完成,如何运行其他backgroundWorker?
private void button1_Click(object sender, EventArgs e)
{
CopyWorker.RunWorkerAsync();
EnkripsiWorker.RunWorkerAsync();
CompressWorker.RunWorkerAsync();
}
我想尝试一键运行,但只有第一个BackgroundWorker正在运行。那么,如何运行所有BackgroundWorker。是否可以做到?
像这样private void button1_Click(object sender, EventArgs e)
{
CopyWorker.RunWorkerAsync();
if (CopyWorker.RunWorkerCompleted == true)
{
EncryptWorker.RunWorkerAsync();
}
if (EnkripsiWorker.RunWorkerCompleted == true)
{
CompressWorker.RunWorkerAsync();
}
}
我修好了,代码是正确的 [编辑]
CopyWorker.RunWorkerAsync();
CopyWorker.RunWorkerCompleted += (s, a) => EnkripsiWorker.RunWorkerAsync();
EnkripsiWorker.RunWorkerCompleted += (s, a) => Compress.RunWorkerAsync();
答案 0 :(得分:1)
在之前的BackgroundWorker
BackgroundWorker
事件中开始每个连续的RunWorkerCompleted
。
private void CopyWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error == null) // no error occurred
EnkripsiWorker.RunWorkerAsync();
}
private void EnkripsiWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error == null)
CompressWorker.RunWorkerAsync();
}
此外,如果e.Error
不是null
,那么DoWork
事件会引发异常,您可以相应地处理它(记录它,显示消息,等等)。
如果你想要真正详细,而不是在RunWorkerCompleted
事件中做任何其他事情(包括错误检查!),你可以缩短它:
CopyWorker.RunWorkerCompleted += (s, a) => EnkripsiWorker.RunWorkerAsync();
EnkripsiWorker.RunWorkerCompleted += (s, a) => CompressWorker.RunWorkerAsync();
CopyWorker.RunWorkerAsync();
虽然这样做没有多大意义,因为你可以组合三个线程。至少在第一个例子中,在开始下一个帖子之前,有机会在RunWorkerCompleted
事件中做其他事情。