Ok, I am Using: C# with Windows Forms
I have a backgroundwork, which works. Now I wanted to create a cancellation button, but even though I told it to cancel and the backgroundwork accepts that, it continues to run the executable it triggers.
I have a cancel button with following code
private void cancelBackup_Click(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync();
displayResults.Text = "Operation Cancelled";
}
And the background worker code is here:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
String invoer = comboboxDriveLetter.Text;
invoer = invoer.Remove(2);
ProcessStartInfo pStartInfo = new ProcessStartInfo("C:\\windows\\system32\\wbadmin.exe", " START BACKUP -backuptarget:" + invoer + " -include:c: -AllCritical -quiet");
pStartInfo.CreateNoWindow = true;
pStartInfo.UseShellExecute = false;
pStartInfo.RedirectStandardInput = true;
pStartInfo.RedirectStandardOutput = true;
pStartInfo.RedirectStandardError = true;
Process process1 = new Process();
process1.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
process1.ErrorDataReceived += new DataReceivedEventHandler(ErrorHandler);
pStartInfo.Verb = "runas";
process1.StartInfo = pStartInfo;
process1.SynchronizingObject = displayResults;
process1.Start();
process1.BeginOutputReadLine();
process1.WaitForExit();
}
When I click the button to cancel, it goes through the action, but the backup just continues, as the richtextbox ends up displaying the entire thing
Operation CancelledCreating a shadow copy of the volumes specified for backup...
Creating a shadow copy of the volumes specified for backup...
Creating a shadow copy of the volumes specified for backup...
Creating a shadow copy of the volumes specified for backup...
The backup of volume SYSTEM (1.99 GB) successfully completed.
Creating a backup of volume OS(C:), copied (0%).
Creating a backup of volume OS(C:), copied (0%).
Creating a backup of volume OS(C:), copied (8%).
Creating a backup of volume OS(C:), copied (55%).
Creating a backup of volume OS(C:), copied (82%).
The backup of volume OS(C:) successfully completed.
The backup operation successfully completed.
Summary of the backup operation:
------------------
The backup of volume SYSTEM (1.99 GB) successfully completed.
The backup of volume OS(C:) successfully completed.
What am I doing wrong?
The cancellation of BackgroundWorker is cooperative. That means that the code inside DoWork should periodically check a flag and quit when requested.
And process1.Start();
will of course not respond to that flag.
You could try calling process1.Kill();
from the Cancel button but I'm not sure whether that is thread-safe.
So probably this:
//process1.WaitForExit();
while (! process1.WaitForExit(100))
{
if (bgw.CancellationPending)
{
e.cancel = true;
process1.Kill();
}
}