I just started learning wpf, so do not throw slippers :) I have a function that creates a new window with a progress bar, receives files via sftp (SSH.NET) and displays the progress of receiving these files. If you do this:

 foreach (var file in files) { if (!file.IsDirectory && !file.IsSymbolicLink) { using (Stream fileStream = File.OpenWrite(System.IO.Path.Combine("photo_viewer_temp\\" + nowGetId.ToString(), file.Name))) { sftp.DownloadFile(file.FullName, fileStream); } } nowDownloaded++; downloadProgressBar.Value = nowDownloaded; progressTextBlock.Text = nowDownloaded.ToString() + " из " + filesCounter.ToString(); } 

that window just hangs. The program loads and saves files, but the window is not updated, windows shows a round cursor ("thinks"). But if you do this:

 foreach (var file in files) { if (!file.IsDirectory && !file.IsSymbolicLink) { using (Stream fileStream = File.OpenWrite(System.IO.Path.Combine("photo_viewer_temp\\" + nowGetId.ToString(), file.Name))) { sftp.DownloadFile(file.FullName, fileStream); } } nowDownloaded++; downloadProgressBar.Value = nowDownloaded; progressTextBlock.Text = nowDownloaded.ToString() + " из " + filesCounter.ToString(); MessageBox.Show("Debug"); } 

Then everything starts to work. How to make it update without MessageBox?

    1 answer 1

    In general, I would recommend researching MVVM technology for this case, but there is an easy way to do it without it, just postpone updating the data to the dispatcher from a task, for example:

     Task.Run(() => { foreach (var file in files) { Dispatcher.CurrentDispacher.Invoke(() => { if (!file.IsDirectory && !file.IsSymbolicLink) { using (Stream fileStream = File.OpenWrite(System.IO.Path.Combine("photo_viewer_temp\\" + nowGetId.ToString(), file.Name))) { sftp.DownloadFile(file.FullName, fileStream); } } nowDownloaded++; downloadProgressBar.Value = nowDownloaded; progressTextBlock.Text = nowDownloaded.ToString() + " из " + filesCounter.ToString(); }); } }); 
    • Why, in this case, is the file download sent to Dispatcher? That is, in the thread of the thread pool, it is only foreach, and all the hard work goes to each UI thread in the iteration. This code does not solve the problem. - CasperSC