I have the following method to download files from a web address using httpwebrequest. I am downloading 150 files contained in a list. This may take say 30 mins max. When I run my service my webrequests keep timeing out and I'm not sure why? I'm guessing it is creating 150 tasks and processing as many as it can but timing out after the timeout period on some of the tasks. What is going on in my method?
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;
}
EDIT
Exception thrown at line stated in code:
Exception: An exception of type 'System.Net.WebException' occurred in System.dll but was not handled in user code
Additional information: The operation has timed out
The error is thrown after 3 minutes and 20 seconds after the first download begins