我有以下代码从HTTPServer下载一组文件。它给出了前几个文件的响应,后来卡在了响应中。我可以从我创建的日志文件中验证这一点。在日志文件中,它为第三个文件写“ webresponse之前”,但从未到达“ webresponse之后”。我已经在利用webresponse了。这里可能会发生什么?
Logger.WriteToLog("url = " +url);
// Create a request to the file we are downloading
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Timeout = 120000;
webRequest.ReadWriteTimeout = 300000;
// Set default authentication for retrieving the file
//webRequest.Credentials = new NetworkCredential(GlobalVariables.username, GlobalVariables.password);
webRequest.UseDefaultCredentials = true;
// Retrieve the response from the server
Logger.WriteToLog("Before webresponse");
using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
{
Logger.WriteToLog("After webresponse");
// Ask the server for the file size and store it
//Int64 fileSize = webResponse.ContentLength;
// Open the URL for download
using (Stream strResponse = webResponse.GetResponseStream())
{
// Create a new file stream where we will be saving the data (local drive)
strLocal = File.Create(destFilePath);
// Loop through the buffer until the buffer is empty
while ((bytesSize = strResponse.Read(downBuffer, 0, downBuffer.Length)) > 0)
{
if (isPaused)
waitRun_m.WaitOne();
if (isCanceled)
break;
strLocal.Write(downBuffer, 0, bytesSize);
// Invoke the method that updates the form's label and progress bar
UpdateProgessCallback(mediaName, bytesSize);
};
strResponse.Close();
}
}
我尝试了ServicePoint类方法,现在可以正常工作了。我所做的是,在为webrequest添加了readwritetimeout之后,我使用以下语句为连接组分配了名称:
webRequest.ConnectionGroupName = some_name;
当关闭连接时:
webRequest.ServicePoint.CloseConnectionGroup(some_name);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句