一起运行两个BackgroundWorkers

时间:2017-03-29 15:03:58

标签: c# winforms bots telegram telegram-bot

我想并行运行2个BackgroundWorkers。我该如何实现它?在我的下面的代码中,backgroundWorker2不起作用:

private void Form1_Load(object sender, EventArgs e)
{
  backgroundWorker1.RunWorkerAsync();
  backgroundWorker2.RunWorkerAsync();
}

1 个答案:

答案 0 :(得分:2)

请改用Task Parallel Library。更新的做事方式。

使用Parallel.Invoke的伪代码:

Parallel.Invoke(() => SomeMethod(), () => SomeOtherMethod());

Task的伪代码:

async Task SomeMethod() {  }
async Task SomeOtherMethod() {  }  

Task task1 = SomeMethod();
Task task2 = SomeOtherMethod();
await Task.WhenAll(task1,task2);
// get results task1.Result and task2.Result