wpfmultithreadingprogress-bardispatcherfile.readalllines

Wpf ProgressBar not updating During Threading Operation


i have a C# wpf project with a progress bar. i am trying to update the progressbar during a threading operation but nothing happens. using dispatcher should have done the job but it is not working. here is a sample code: many thanks!

private async void search(string[] files)
{
    progressBar.Maximum = files.Length;
    List<System.Threading.Tasks.Task> searchTasks = new List<System.Threading.Tasks.Task>();
    foreach (string file in files)
    {
        searchTasks.Add(Task.Run(() =>
        {
            this.Dispatcher.Invoke(() =>
            {
                progressBar.Value = progressBar.Value + 1;
                File.ReadAllLines(file);
                //do somthing with the lines
            });
        }));
    }
    await System.Threading.Tasks.Task.WhenAll(searchTasks);
    progressBar.Value = 0;
}

edit: my misatake has been pointed out correctly File.ReadAllLines(file); should be outside the dispatcher


Solution

  • The problem with your implementation is you are trying to run list of tasks. When tasks are executed all the task runs simultaneously on a thread pool.

    Hence all tasks might get executed at the same time and all gets completed quickly.

    The reason you are not able to see UI progress bar update is coz of files are being read on UI thread itself which will hang your Ui. UI won't get updated until all tasks are completed. And when all tasks are completed, you are setting the value to 0 again. Hence not observable to user.

    What you could try:

    foreach (string file in files)
    {
        searchTasks.Add(Task.Run(() =>
        {
            this.Dispatcher.Invoke(() =>
            {
                progressBar.Value = progressBar.Value + 1;
            });
                File.ReadAllLines(file);
                //do somthing with the lines
        }));
    }