Click here to Skip to main content
15,892,809 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how to handle backgroundworker(Cancel, Progressbar, Completed, ...) when use recursive method inside it?

C#
private static void Copyy(string s,string d)
{
    //Exist folder of destination?
    if (!Directory.Exists(d))
        Directory.CreateDirectory(d);

    //Get info folder of destination
    var dir = new DirectoryInfo(s);
        //1
        FileInfo[] files = dir.GetFiles("*.*", SearchOption.TopDirectoryOnly);
    foreach (var file in files)
    {
        File.Copy(file.FullName, Path.Combine(d, Path.GetFileName(file.FullName)), true);

    }
        //2
        DirectoryInfo[] folders = dir.GetDirectories();
        if (folders.Count() != 0)
            foreach (var folder in folders)
                Copyy(folder.FullName, Path.Combine(d, folder.FullName.Replace(s, "").TrimStart('\\')));
}


C#
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
  {
      try
      {
          BeginInvoke((MethodInvoker)delegate
          {
              lblMessage.Text = String.Empty;
              btnUpdate.Enabled = false;
              But_Cancel.Enabled = true;

              var dir = new DirectoryInfo((string)e.Argument);
              FileInfo[] files = dir.GetFiles("*.*", SearchOption.TopDirectoryOnly);
              progressBar.Minimum = 0;
              progressBar.Maximum = files.Length;
          });

          Copyy((string)e.Argument, @"c:\Test");//<<---------------***

          BeginInvoke((MethodInvoker)delegate
          {
              btnUpdate.Enabled = true;
              But_Cancel.Enabled = false;
              this.lblMessage.Text = @"Done!";
          });
      }
      catch (Exception ex)
      {
          return;
      }
  }
Posted
Comments
George Jonsson 30-Oct-14 3:42am    
Try passing the parameter 'DoWorkEventArgs e' into your Copyy method.
BillWoodruff 30-Oct-14 3:55am    
What errors are occurring now: how is your current code not working for you ?
Philippe Mori 30-Oct-14 21:46pm    
By the way initialization code that is related to the UI should be executed from the calling thread before calling RunWorkerAsync and final code should be executed is completed Handler.

1 solution

The three things you mentioned (Cancel, Progressbar, Completed) are completely different, and need a differenet approach.

Completed is the easy one: it's automatically generated when the DoWork event handler exits. So there is nothing you need to do to handle this, as all background processing ends at that point.

Cancel is not complex, it just takes a little work: you need a class level bool which is set to true in the But_Cancel Click event handler and checked at the top of your Copyy method. If it's true, return immediately.

A ProgressBar is more complex - you need to have access to the BackgroundWorker instance in order to signal the ProgressChanged event via it's ReportProgress method. Fortunately, it is passed to the DoWork event handler as the sender parameter, so all you need to do is cast that to a BackgroundWorker and pass it into your Copyy method as a parameter:
C#
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
    {
    BackgroundWorker worker = sender as BackgroundWorker;
    if (worker != null)
        {

C#
private static void Copyy(string s,string d, BackgroundWorker worker = null)
    {
Then, when you want to report progress in Copyy:
C#
if (worker != null)
    {
    worker.ReportProgress(percentage);
    }
And pass the worker value on down when you call each recursive instance.


But...you do realize that you don;t need to be recursive at all? You can use Directory.GetFiles to return the full path to all files in a folder, including subdirectories as one line, eliminating the need to recursively process the folders.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900