Search code examples
c#backgroundworkercancellation

how to cancel DoWork in Backgroundworker


i know this's not the first question about Canceling BackGroundWorker but i didn't find the answer to solve my problem.
i have a method that sends file .. im using backgroundworker to call it ..
So how can i cancel backgroundworker in the middle of sending the file .. i mean where should i put

if (backgroundWorker1.CancellationPending == true)
   {
       e.Cancel = true;
       break;
   }

here's the code :

 private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        List<object> job = (List<object>)e.Argument;
        string srcPath = (string)job[0];
        string destPath = (string)job[1];
        SendFile(srcPath, destPath);
    }

Send Method :

 private void SendFile(string srcPath, string destPath)
    {
        string dest = Path.Combine(destPath, Path.GetFileName(srcPath));
        using (fs = new FileStream(srcPath, FileMode.Open, FileAccess.Read))
        {
            try
            {
                long fileSize = fs.Length;
                if (sizeAll == 0)
                    sizeAll = fileSize;
                sum = 0;
                int count = 0;
                data = new byte[packetSize];
                SendCommand("receive<" + dest + "<" + fs.Length.ToString());
                ProgressLabel(++fileCount, allFileCount);
                InfoLabel("Sending " + srcPath, "busy");
                while (sum < fileSize)
                {
                    count = fs.Read(data, 0, data.Length);
                    network.Write(data, 0, count);
                    sum += count;
                    sumAll += count;
                    backgroundWorker1.ReportProgress((int)((sum * 100) / fileSize));
                }
                network.Flush();
            }
            finally
            {
                network.Read(new byte[1], 0, 1);
                CloseTransfer();
            }
        }
    }

i should check for CancellationPending in the while() loop in send method .. but i can't get to [e.Cancel] of backgroundworker from this method .. what shall i do?


Solution

  • The DoWorkEventArgs e could be passed as third argument in SendFile:

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) 
    { 
        List<object> job = (List<object>)e.Argument; 
        string srcPath = (string)job[0]; 
        string destPath = (string)job[1]; 
        SendFile(srcPath, destPath, e); 
    } 
    

    then SendFile will be

    private void SendFile(string srcPath, string destPath, DoWorkEventArgs e)   
    

    and in your loop, after ReportProgress

       if (backgroundWorker1.CancellationPending == true)    
       {    
           e.Cancel = true;    
           return; // this will fall to the finally and close everything    
       }