Ftp requests in Windows Service Timing out

I have windows service that periodically upload file upload file on an FTP server. I have set,

ServicePointManager.DefaultConnectionLimit = 100;

and I have,

   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);
        }

Its work fine for 100 or more request but after 100 or more I am continuously getting,

System.Net.WebException: The operation has timed out.
   at System.Net.FtpWebRequest.CheckError()
   at System.Net.FtpWebRequest.GetResponse()

Why this is happening.

Update: I am thinking to move in http

Upvotes: 2

Views: 2436

Answers (1)

Hans Passant
Hans Passant

Reputation: 941724

        request.GetResponse();

Your snippet is very incomplete, but surely the problem started here. GetResponse() returns an FtpWebResponse object, it is crucial that your code calls Close() or disposes it to ensure that the Ftp connection is closed.

If you forget then you will have 100 active connections after downloading 100 files and trip the ServicePointManager.DefaultConnectionLimit. The garbage collector doesn't run often enough to keep you out of trouble. After which any subsequent downloads will die with a timeout. Fix:

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

Which uses the reliable way to ensure that the connection will be closed, even if the code falls over with an exception. If you still have trouble then diagnose with, say, SysInternals' TcpView utility. It is a good way to see active connections.

Upvotes: 6

Related Questions