c# - Windows 服务中的 Ftp 请求超时

标签 c# ftp windows-services

我有 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/

相关文章:

c# - 大型 c# 应用程序的命名空间组织概念

python - 使用 NOOP 命令检查 FTP 连接是否有效

c# - JavaScript中的条件语句

c# - 加载带有大量控件的繁重 UI 的最佳方式

linux - SFTP 连接问题与密码

dependency-injection - Windows 服务和最佳实践上的 Akka.NET DI

windows-services - .msi 和 setup.exe 文件之间有什么具体区别?

c# - Debug.WriteLine() 未命中

c# - 通过 C# 获取所有 CSP 和/或 CNG 提供商的列表?

php - 如何使用 php 运行 ftp 服务器?