如果第一个BackgroundWorker在一个方法中完成,如何运行其他BackgroundWorker

时间:2014-02-04 01:02:16

标签: c# backgroundworker

如果主要后台工作者在一种方法中完成,如何运行其他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();

1 个答案:

答案 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事件中做其他事情。