I am adding a progress bar for my WPF application. I want to show the real-time progress on the progress bar along with the count of generated files in real time like 4/100 files generated etc. Below are the two actions and the Tasks that are executing these actions
Action Generate = new Action(() =>
{
foreach (string file in Files)
{
//all the logic to generate files
using (var streamWriter = new StreamWriter(newFileName, false, Encoding.Default))
{
foreach (string segment in newFile)
{
streamWriter.WriteLine(segment);
}
filesGenerated++;
//I need to do the second action here
}
}
});
Action ShowProgressBar = new Action(() =>
{
progressBar.Value = filesGenerated
lblProgress.Content = filesGenerated + " File(s) Generated.";
});
Task GenerateTask = Task.Factory.StartNew(() => Generate());
Task ShowProgressBarTask = new Task(ShowProgressBar);
I have tried to nest the tasks but it is not working. What should I be doing to show real-time progress in progress bar.
Run your file creation code in another thread
Set the value of progress bar in foreach loop by using Dispatcher cause you on another thread and can not change UI control from that one.
Basically you done.