我正在使用BackGroundWorker
来传输backgorund中的文本文件。
当这个完成时,我想同时运行两个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
}
答案 0 :(得分:3)
你不要等待任何事情。只需使用task1
和task2
Task.WaitAll(new Task[]{task1, task2});
<强>更新强>
使用MessageBox,您可以完成任务以完成其工作。