在BackgroundWorker完成后同时运行任务

本文关键字:运行 任务 BackgroundWorker | 更新日期: 2023-09-27 18:18:25

我使用BackGroundWorker在后台流式传输文本文件。

当这完成后,我想同时运行两个Tasks,这涉及到两个计算繁重的方法。这些方法使用流数据进行计算。

不知怎么的,我被困住了。第一部分执行完毕,我就可以流式传输数据了。但是涉及计算的第二部分不会执行。

private readonly BackgroundWorker _streamworker = new BackgroundWorker();
public MainWindow()
{
    InitializeComponent();
    _streamworker.WorkerReportsProgress = true;
    _streamworker.WorkerSupportsCancellation = true;
    _streamworker.DoWork += StreamData;
    _streamworker.RunWorkerCompleted += worker_RunWorkerCompleted;
    _streamworker.RunWorkerAsync();
}
private void StreamData(object sender, DoWorkEventArgs e)
{
    // Stream a Text file here
}
private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    var task1 = Task.Factory.StartNew(HeavyMethod1);
    var task2 = Task.Factory.StartNew(HeavyMethod2);
    Task.WaitAll();
    // After the calculations have ended
    // Do something with the calculate results here
}
private void HeavyMethod1()
{
    // Some heavy calculations
}
private void HeavyMethod2()
{
    // Some heavy calculations that are not 
    // related to the ones in HeavyMethod1
}

更新:一个非常非常奇怪的事情,我已经注意到,如果我把MessageBox.Show("");之前的计算一切都很好!

private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    var task1 = Task.Factory.StartNew(HeavyMethod1);
    var task2 = Task.Factory.StartNew(HeavyMethod2);
    Task.WaitAll();
    MessageBox.Show("");
    // After the calculations have ended
    // Do something with the calculate results here
}

在BackgroundWorker完成后同时运行任务

你不需要等待任何事情。只用task1task2

Task.WaitAll(new Task[]{task1, task2});

使用MessageBox,您可以为任务提供完成其作品的机会。