我有 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() 返回一个 FtpWebResponse 对象,您的代码调用 Close() 或处置它以确保关闭 Ftp 连接至关重要。
如果您忘记了,那么您将在下载 100 个文件后拥有 100 个事件连接并超出 ServicePointManager.DefaultConnectionLimit。垃圾收集器的运行频率不足以让您远离麻烦。之后,任何后续下载都将因超时而终止。修复:
using (var response = request.GetResponse()) {
// Do stuff
//...
}
它使用可靠的方式来确保连接将被关闭,即使代码因异常而失败。如果您仍然遇到问题,请使用 SysInternals 的 TcpView 实用程序进行诊断。这是查看事件连接的好方法。
关于c# - Windows 服务中的 Ftp 请求超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29058494/