簡體   English   中英

如何在Backgroundworker中取消DoWork

[英]how to cancel DoWork in Backgroundworker

我知道這不是關於取消BackGroundWorker的第一個問題,但我找不到解決問題的答案。
我有一個發送文件的方法..我使用backgroundworker來調用它..
那么如何在發送文件的過程中取消后台工作者...我的意思是我應該放在哪里

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

這是代碼:

 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);
    }

發送方式:

 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();
            }
        }
    }

我應該在send方法的while()循環中檢查CancellationPending ..但是我不能從這個方法到[background.de]的背景工作者...我該怎么辦?

DoWorkEventArgs e可以作為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); 
} 

然后SendFile會

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

在ReportProgress之后的循環中

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

把它放在你的while循環中:

while (sum < fileSize)
{
    if (worker.CancellationPending)
    {
        e.Cancel = true;
        break;
    }

    count = fs.Read(data, 0, data.Length);
    network.Write(data, 0, count);
    sum += count;
    sumAll += count;
    backgroundWorker1.ReportProgress((int)((sum * 100) / fileSize));
}
network.Flush();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM