简体   繁体   中英

How to Update TextBlock after copy a file in FOR Loop in C# WPF

Hi I want copy some file in Hard and after each copy TextBlock increase one number

foreach (string newPath in Directory.GetFiles(clipsSource, "*.*", SearchOption.AllDirectories))
{
     i++;
     File.Copy(newPath, newPath.Replace(clipsSource, Dest + "\\clips"), true);
     copyProgressLbl.Text = i.ToString();
}

But TextBlock Not Updated in each loop What do I do?

here is a sample to run the code async and update the TextBlock so it does not block the UI.

Task.Run(() =>
{
    foreach (string newPath in Directory.GetFiles(clipsSource, "*.*", SearchOption.AllDirectories))
    {
        i++;
        File.Copy(newPath, newPath.Replace(clipsSource, Dest + "\\clips"), true);
        Dispatcher.Invoke(() => copyProgressLbl.Text = i.ToString());
    }
});

Idea is to run the blocking methods in Tasks and update the UI controls via Dispatcher when needed.

alternate method using ThreadPool if unable to use Tasks

ThreadPool.QueueUserWorkItem(delegate
{
    foreach (string newPath in Directory.GetFiles(clipsSource, "*.*", SearchOption.AllDirectories))
    {
        i++;
        File.Copy(newPath, newPath.Replace(clipsSource, Dest + "\\clips"), true);
        Dispatcher.Invoke(() => copyProgressLbl.Text = i.ToString());
    }
});

While @pushpraj had the right idea to call your update code asynchronously, you might have more luck using this code instead:

foreach (string newPath in Directory.GetFiles(clipsSource, "*.*", SearchOption.AllDirectories))
{
    i++;
    File.Copy(newPath, newPath.Replace(clipsSource, Dest + "\\clips"), true);
    Task.Factory.StartNew(() => copyProgressLbl.Text = i.ToString());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM