【发布时间】:2014-10-30 13:31:50
【问题描述】:
在form1的顶部我做了:
WebClient Client;
然后在构造函数中:
Client = new WebClient();
Client.DownloadFileCompleted += Client_DownloadFileCompleted;
Client.DownloadProgressChanged += Client_DownloadProgressChanged;
然后我每分钟都会调用这个方法:
private void fileDownloadRadar()
{
if (Client.IsBusy == true)
{
Client.CancelAsync();
}
else
{
Client.DownloadProgressChanged += Client_DownloadProgressChanged;
Client.DownloadFileAsync(myUri, combinedTemp);
}
}
每分钟它都会从网站下载一张图片,每次都是相同的图片。 直到现在在下载完成事件中抛出此异常之前,它都工作了 24 小时以上没有问题:
private void Client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
{
timer1.Stop();
span = new TimeSpan(0, (int)numericUpDown1.Value, 0);
label21.Text = span.ToString(@"mm\:ss");
timer3.Start();
}
else if (!e.Cancelled)
{
label19.ForeColor = Color.Green;
label19.Text = "חיבור האינטרנט והאתר תקינים";
label19.Visible = true;
timer3.Stop();
if (timer1.Enabled != true)
{
if (BeginDownload == true)
{
timer1.Start();
}
}
bool fileok = Bad_File_Testing(combinedTemp);
if (fileok == true)
{
File1 = new Bitmap(combinedTemp);
bool compared = ComparingImages(File1);
if (compared == false)
{
DirectoryInfo dir1 = new DirectoryInfo(sf);
FileInfo[] fi = dir1.GetFiles("*.gif");
last_file = fi[fi.Length - 1].FullName;
string lastFileNumber = last_file.Substring(82, 6);
int lastNumber = int.Parse(lastFileNumber);
lastNumber++;
string newFileName = string.Format("radar{0:D6}.gif", lastNumber);
identicalFilesComparison = File_Utility.File_Comparison(combinedTemp, last_file);
if (identicalFilesComparison == false)
{
string newfile = Path.Combine(sf, newFileName);
File.Copy(combinedTemp, newfile);
LastFileIsEmpty();
}
}
if (checkBox2.Checked)
{
simdownloads.SimulateDownloadRadar();
}
}
else
{
File.Delete(combinedTemp);
}
File1.Dispose();
}
}
现在它在 if(e.Error != null) 内停止 上线:timer1.Stop();
然后我在错误中看到错误: 这是堆栈跟踪:
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result)
at System.Net.WebClient.DownloadBitsResponseCallback(IAsyncResult result)
我怎样才能解决这个问题,这样它就不会再发生了?为什么会这样?
编辑:
我尝试将fileDownloadRadar方法改成这样,每次都释放客户端:
private void fileDownloadRadar()
{
using (WebClient client = new WebClient())
{
if (client.IsBusy == true)
{
client.CancelAsync();
}
else
{
client.DownloadFileAsync(myUri, combinedTemp);
}
}
}
问题是在构造函数中我使用的是客户端,这里是客户端两个不同的 Webclient 变量。
我该如何解决这个问题和异常?
这是网站的网站墨水,其中包含我每分钟下载的图像。 仍然不确定为什么在它工作超过 24 小时没有问题后我得到这个异常。 现在我再次运行该程序并且它正在工作,但我想知道我是否会在明天或有时在接下来的几个小时内再次遇到此异常。
【问题讨论】:
-
更新了我的问题。我正在尝试与 Webclient 一起使用,但不确定这是异常的解决方案。第二个问题是如何使用 Using,因为现在我有两个不同的 WebClient 变量,这是错误的。
-
您描述的错误与
using无关。如果您想在类级别使用单个WebClient实例,则下载方法中不应包含using语句。你有没有看我的回答?