[英]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. 我知道这不是关于取消BackGroundWorker的第一个问题,但我找不到解决问题的答案。
i have a method that sends file .. im using backgroundworker to call it .. 我有一个发送文件的方法..我使用backgroundworker来调用它..
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? 我应该在send方法的while()循环中检查CancellationPending ..但是我不能从这个方法到[background.de]的背景工作者...我该怎么办?
The DoWorkEventArgs e could be passed as third argument in SendFile: 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);
}
then SendFile will be 然后SendFile会
private void SendFile(string srcPath, string destPath, DoWorkEventArgs e)
and in your loop, after ReportProgress 在ReportProgress之后的循环中
if (backgroundWorker1.CancellationPending == true)
{
e.Cancel = true;
return; // this will fall to the finally and close everything
}
Put it in your while
loop: 把它放在你的
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.