I would like to understand the following behaviour.
I have WPF application with button click event handler in which I start Parallel.ForEach
. In each loop I update UI via Dispatcher. After the Parallel.Foreach
I do the "final update" of the UI. However this "final update" actually happens before any of the updates from the Dispatcher
. Why is it happening in this order?
private void btnParallel_Click(object sender, RoutedEventArgs e)
{
txbResultsInfo.Text = "";
Parallel.ForEach(_files, (file) =>
{
string partial_result = SomeComputation(file);
Dispatcher.BeginInvoke(new Action(() =>
{
txbResultsInfo.Text += partial_result + Environment.NewLine;
}));
});
txbResultsInfo.Text += "-- COMPUTATION DONE --"; // THIS WILL BE FIRST IN UI, WHY?
//Dispatcher.BeginInvoke(new Action(() => txbResultsInfo.Text += "-- COMPUTATION DONE --"; - THIS WAY IT WILL BY LAST IN UI
}
My intuitive expectation was that the code continues after all branches of the Parallel.ForEach
loops are finished, meaning the Dispatcher
has received all requests for UI update and started to execute them and only then we continue to update the UI from the rest of the handler method.
But the "-- COMPUTATION DONE --"
actually always appears first in the textBlock. Even if I put Task.Delay(5000).Wait()
before the "done computation" update. So it is not just a matter of speed, it is actually sorted somehow that this update is happening before updates from Dispatcher.
If I put the "done computation" update to dispatcher as well, it behaves as I would expect and is at the end for the text. But why does this needs to be done via dispatcher as well?