Windows服务定时中的Ftp请求

时间:2015-03-15 08:01:26

标签: 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

1 个答案:

答案 0 :(得分:5)

        request.GetResponse();

您的代码段非常不完整,但问题肯定是从这里开始的。 GetResponse()返回一个FtpWebResponse对象,您的代码调用Close()或处置它以确保Ftp连接关闭是至关重要的。

如果您忘记了,那么在下载100个文件后,有100个活动连接,并跳转ServicePointManager.DefaultConnectionLimit。垃圾收集器的运行频率不足以让您远离麻烦。之后任何后续下载都会因超时而死亡。修正:

using (var response = request.GetResponse()) {
    // Do stuff
    //...
}

使用可靠的方法确保连接将被关闭,即使代码因异常而崩溃。如果您仍有问题,请使用SysInternals的TcpView实用程序进行诊断。这是查看活动连接的好方法。

相关问题