C# 从httpwebrequest异步下载文件会引发超时错误
我使用以下方法使用httpwebrequest从web地址下载文件。我正在下载列表中包含的150个文件。这可能需要最多30分钟。当我运行我的服务时,我的webrequests不断超时,我不知道为什么?我猜它正在创建150个任务并处理尽可能多的任务,但在某些任务超时后超时。我的方法怎么了C# 从httpwebrequest异步下载文件会引发超时错误,c#,asynchronous,httpwebrequest,task-parallel-library,task,C#,Asynchronous,Httpwebrequest,Task Parallel Library,Task,我使用以下方法使用httpwebrequest从web地址下载文件。我正在下载列表中包含的150个文件。这可能需要最多30分钟。当我运行我的服务时,我的webrequests不断超时,我不知道为什么?我猜它正在创建150个任务并处理尽可能多的任务,但在某些任务超时后超时。我的方法怎么了 try { //Download File here Task t = new Task(() => { byte[] lnBuffer;
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;
}
编辑
在代码中指定的行引发异常:
异常:在中发生“System.Net.WebException”类型的异常
System.dll,但未在用户代码中处理
其他信息:操作已超时
在第一次下载开始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
}
你怎么称呼这个方法?您确定您的服务器可以同时接受150个呼叫吗?更重要的是,你不需要线程来做IO绑定的工作。我在客户端的foreach循环中调用这个方法。我甚至不知道如何检查我的服务器是否可以接受150个并发调用,以及为什么我不需要线程来执行IO工作?我想我的线程会在每次下载后等待,然后再转到下一个?旁注:用Stream.copy直接复制到FileStream。或者:新建WebClient.DownloadFileurl,路径。连接限制设置为什么?默认值不是2吗?!我从中获得了下载算法,但我将研究DownloadFile方法。连接限制设置为服务器端还是客户端?当我的程序超时时,2分钟听起来差不多是正确的