I am trying to update the progress bar while running a Parallel.Foreach
, but during execution nothing happens. Progressbar gets updated only when the For loop end. How can I make this code work?
XAML
<StackPanel>
<Grid x:Name="LoadProgressGrid" Height="100"
Visibility="Visible">
<ProgressBar x:Name="LoadProgress"
Maximum="100"
Minimum="1" />
<TextBlock Margin="0,0,0,-5"
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontSize="16"><Run Text="Import Progress"/></TextBlock>
</Grid>
<Button Height="35" Width="100" Margin="0,10" Content="Test" Click="Test_Click"/>
</StackPanel>
C#
private void Test_Click(object sender, RoutedEventArgs e)
{
decimal current=0;
List<string> lst = new List<string>();
lst.Add("Foo");
lst.Add("Foo");
lst.Add("Foo");
lst.Add("Foo");
decimal max = 100000;
var uiFactory = new TaskFactory(TaskScheduler.FromCurrentSynchronizationContext());
Parallel.ForEach(lst, (data) =>
{
for (int i = 0; i < max; i++)
{
// Use the uiFactory above:
// Note the need for a temporary here to avoid closure issues!
current = current + 1;
uiFactory.StartNew( () => LoadProgress.Value = (double)(current/max)*100);
}
});
MessageBox.Show("Done!");
}