gpt4 book ai didi

c# - 如何取消Backgroundworker中的DoWork

转载 作者:行者123 更新时间:2023-11-30 13:33:09 25 4
gpt4 key购买 nike

我知道这不是关于取消 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 .. 但我无法从该方法到达 backgroundworker 的 [e.Cancel] .. 我该怎么办?

最佳答案

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
}

关于c# - 如何取消Backgroundworker中的DoWork,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9642378/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com