Question Cancel function does not work with backgroundWorker?

ken76

Member
Joined
Nov 15, 2018
Messages
23
Programming Experience
5-10

KenEkholm-3624
asked • 1 sec ago
Actions
Cancel function does not work this code below. Can someone tell me what is wrong with this code?
C#:
   private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {

Array.ForEach(originalFiles, (originalFileLocation) =>
                {
                    FileInfo originalFile = new FileInfo(originalFileLocation);
                    FileInfo destFile = new FileInfo(originalFileLocation.Replace(sourcePath, destPath));
                    if (backgroundWorker1.CancellationPending == true)
                    {
                        e.Cancel = true;
                        return;
                    }

                    if (destFile.Exists)
                    {
                       if (originalFile.Length != destFile.Length || originalFile.LastWriteTime != destFile.LastWriteTime)
                       {
                           originalFile.CopyTo(destFile.FullName, true);
                           count2++;
                           answer = count2 / count * 100;
                           answer = Math.Round(answer);
                           backgroundWorker1.ReportProgress(Decimal.ToInt32(answer));
                           textFile = "Copying file " + destFile.FullName.ToString();
                           logFile.Add(textFile);
                            countLines++;
                       }
                    }
                    else
                    {
                        Directory.CreateDirectory(destFile.DirectoryName);
                        originalFile.CopyTo(destFile.FullName, false);
                        count2++;
                        answer = count2 / count * 100;
                        answer = Math.Round(answer);
                        backgroundWorker1.ReportProgress(Decimal.ToInt32(answer));
                        textFile = "Copying file " + destFile.FullName.ToString();
                        logFile.Add(textFile);
                        countLines++;
                    }
                });
}

  private void buttonCancel_Click(object sender, EventArgs e)
        {
            backgroundWorker1.WorkerSupportsCancellation = true;
            backgroundWorker1.CancelAsync();
            buttonCancel.Enabled = false;
        }
 
My gut instinct is this has something to do with lambda captures, and in particular how that DoWorkEventArgs is being captured. I don't see anywhere in that code where you really need to use Array.ForEach() when you could just use a vanilla foreach and not have to deal with lambda capture issues.

So just change line 4 to:
C#:
foreach(string originalFileLocation in originalFiles)
and line 40 to:
C#:
}
 
Back
Top Bottom