Ftp 请求在 Windows 服务超时
Ftp requests in Windows Service Timing out
我有 windows 服务,可以定期在 FTP 服务器上上传文件。我已经设置了,
ServicePointManager.DefaultConnectionLimit = 100;
我有,
public void MyMethod(string url,
string userName,
string password)
{
try
{
var request = (FtpWebRequest) WebRequest.Create(url);
request.Timeout = GetFtpTimeoutInMinutes()*60*1000;
request.Credentials = new NetworkCredential(userName, password);
request.Method = method;
request.UseBinary = true;
request.UsePassive = true;
request.KeepAlive = false;
request.GetResponse();
}
catch (Exception ex)
{
_logger.Log(ex);
}
对于 100 个或更多的请求它工作正常但是在 100 个或更多之后我不断地得到,
System.Net.WebException: The operation has timed out.
at System.Net.FtpWebRequest.CheckError()
at System.Net.FtpWebRequest.GetResponse()
为什么会这样。
更新:我想搬进http
request.GetResponse();
您的代码片段非常不完整,但问题肯定是从这里开始的。 GetResponse() returns 一个 FtpWebResponse 对象,您的代码调用 Close() 或处置它以确保关闭 Ftp 连接至关重要。
如果您忘记了,那么在下载 100 个文件后您 将 有 100 个活动连接并跳闸 ServicePointManager.DefaultConnectionLimit。垃圾收集器 运行 的频率不足以让您远离麻烦。之后,任何后续下载都将因超时而终止。修复:
using (var response = request.GetResponse()) {
// Do stuff
//...
}
它使用可靠的方式来确保连接将被关闭,即使代码因异常而失败。如果您仍然遇到问题,请使用 SysInternals 的 TcpView 实用程序进行诊断。这是查看活动连接的好方法。
我有 windows 服务,可以定期在 FTP 服务器上上传文件。我已经设置了,
ServicePointManager.DefaultConnectionLimit = 100;
我有,
public void MyMethod(string url,
string userName,
string password)
{
try
{
var request = (FtpWebRequest) WebRequest.Create(url);
request.Timeout = GetFtpTimeoutInMinutes()*60*1000;
request.Credentials = new NetworkCredential(userName, password);
request.Method = method;
request.UseBinary = true;
request.UsePassive = true;
request.KeepAlive = false;
request.GetResponse();
}
catch (Exception ex)
{
_logger.Log(ex);
}
对于 100 个或更多的请求它工作正常但是在 100 个或更多之后我不断地得到,
System.Net.WebException: The operation has timed out.
at System.Net.FtpWebRequest.CheckError()
at System.Net.FtpWebRequest.GetResponse()
为什么会这样。
更新:我想搬进http
request.GetResponse();
您的代码片段非常不完整,但问题肯定是从这里开始的。 GetResponse() returns 一个 FtpWebResponse 对象,您的代码调用 Close() 或处置它以确保关闭 Ftp 连接至关重要。
如果您忘记了,那么在下载 100 个文件后您 将 有 100 个活动连接并跳闸 ServicePointManager.DefaultConnectionLimit。垃圾收集器 运行 的频率不足以让您远离麻烦。之后,任何后续下载都将因超时而终止。修复:
using (var response = request.GetResponse()) {
// Do stuff
//...
}
它使用可靠的方式来确保连接将被关闭,即使代码因异常而失败。如果您仍然遇到问题,请使用 SysInternals 的 TcpView 实用程序进行诊断。这是查看活动连接的好方法。