从httpwebrequest异步下载文件会抛出超时错误
本文关键字:超时 错误 文件 httpwebrequest 异步 下载 | 更新日期: 2023-09-27 18:17:20
我有以下方法使用httpwebrequest从web地址下载文件。我正在下载一个列表中包含的150个文件。这可能最多需要30分钟。当我运行我的服务时,我的网页一直超时,我不知道为什么?我猜它正在创建150个任务并处理尽可能多的任务,但在某些任务的超时时间之后会超时。我的方法发生了什么?
try
{
//Download File here
Task t = new Task(() =>
{
byte[] lnBuffer;
byte[] lnFile;
HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(string.Format("{0}/{1}", Settings1.Default.WebPhotosLocation, f.FileName));
//Breaks on the line below
using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
httpWebRequest.Timeout = 14400000;
httpWebRequest.KeepAlive = true;
using (BinaryReader binaryReader = new BinaryReader(httpWebResponse.GetResponseStream()))
{
using (MemoryStream memoryStream = new MemoryStream())
{
lnBuffer = binaryReader.ReadBytes(1024);
while (lnBuffer.Length > 0)
{
memoryStream.Write(lnBuffer, 0, lnBuffer.Length);
lnBuffer = binaryReader.ReadBytes(1024);
}
lnFile = new byte[(int)memoryStream.Length];
memoryStream.Position = 0;
memoryStream.Read(lnFile, 0, lnFile.Length);
}
}
}
using (System.IO.FileStream lxFS = new FileStream(string.Format(@"{0}'{1}", fileDirectory, f.FileName), FileMode.Create))
{
lxFS.Write(lnFile, 0, lnFile.Length);
}
Log.WriteLine(string.Format("Downloaded File: {0}", f.FullName), Log.Status.Success);
filesDownloaded++;
});
t.Start();
listOfTasks.Add(t);
}
catch (Exception ex)
{
Log.WriteLine(string.Format("There has been an error Downloading File {0}. Error: {1}", f.FullName, ex), Log.Status.Error);
throw;
}
编辑
在代码中声明的行抛出异常:
Exception: System.Net类型的异常。webeexception '发生在但是在用户代码
中没有处理附加信息:The operation has timed out
第一次下载开始后3分20秒抛出错误
原来我是在调用GetResponse后设置超时值。将超时置于该方法调用的上方效果很好。
HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(string.Format("{0}/{1}", Settings1.Default.WebPhotosLocation, f.FileName));
httpWebRequest.Timeout = 14400000;
httpWebRequest.KeepAlive = true;
using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
//Do stuff
}