使用以下代码我通过HTTPWebRequest从数据库下载图像。
BackgroundWorker bgWorker = (BackgroundWorker)sender;
string baseUrl = "http://some path";
int numIterations = 10;
for (int i = 0; i < numIterations; i++)
{
if (bw.CancellationPending == true)
{
e.Cancel = true;
break;
}
else
{
HttpWebRequest request = null;
foreach (var fileName in fileNames)
{
string url = string.Format(baseUrl, fileName);
request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
request.CookieContainer = container;
response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
Image img = Image.FromStream(stream);
img.Save("some path" + fileName);
ZoomThumbnail = img;
ZoomSmall = img;
ZoomLarge = img;
ZoomThumbnail = GenerateThumbnail(ZoomThumbnail, 86, false);
ZoomSmall = GenerateThumbnail(ZoomSmall, 400, false);
ZoomLarge = GenerateThumbnail(ZoomLarge, 1200, false);
if (img != null)
ZoomThumbnail.Save("some path" + fileName + "_Thumb.jpg");
ZoomSmall.Save("some path" + fileName + "_ZoomSmall.jpg");
ZoomLarge.Save("some path" + fileName + "_ZoomLarge.jpg");
System.Threading.Thread.Sleep(200);
}
}
此代码位于ButtonProcess_click下,工作正常。还有一个按钮“取消”。每当用户点击“取消”时,我都希望下载和保存图像的过程停止。有人可以帮忙吗?这是取消按钮的代码,只能禁用“处理”按钮。
ButtonProcess.Enabled = false;
Button btnSender = sender as Button;
btnSender.Enabled = false;
bw.CancelAsync();
答案 0 :(得分:3)
从bw.CancelAsync()
行我想使用BackgroundWorker
。我还猜测上面的代码是由后台工作者执行的。
但是,在该代码中没有任何地方,我可以看到您实际上正在检查是否应该取消该过程。此外,您将在此行中一次性下载图像:
Image img = Image.FromStream(stream);
这不支持取消。所以问题是:
解决方案:
第一个可能的解决方案:
if (bw.CancellationPending)
{
return;
}
第二种可能的解决方案:
Stream stream = response.GetResponseStream();
byte[] buffer = new byte[512];
int bytesRead = 0;
do
{
bytesRead = stream.Read(buffer, 0, buffer.Length);
if (bytesRead > 0)
{
// Save the bytes to a memory stream
}
}
while (bytesRead > 0 && !bw.CancellationPending)
if (!bw.CancellationPending)
img = Image.FromStream(<yourMemoryStream>);