运行2个以上的线程时,FtpWebRequest超时

时间:2012-12-17 20:27:57

标签: c# multithreading ftp

  

可能重复:
  How can I programmatically remove the 2 connection limit in WebClient

我的FTP脚本运行良好,直到我开始尝试一次运行多个线程。在过度调试之后,如果另外两个线程已经在做某事,那么FtpWebRequest只会超时。 (上传,检查文件/目录是否存在或创建目录。)

我已经尝试在ftp类中实现一个锁,这样只有一个线程可以一次创建一个FtpWebRequest(然后在获得c的响应时关闭锁),但这没有帮助。

每个请求都使用它自己的FtpWebRequest对象,所以我不太清楚为什么会这样。使用FileZilla客户端时,我可以将10个文件同时上传到同一个FTP服务器,所以我无法想象它在服务器端是个问题。

.NET中是否有一些静态幕后的东西导致了这个问题?

超时> 2个主题的示例函数:

public class ftp
{
    private string host = null;
    private string user = null;
    private string pass = null;
    private int bufferSize = 2048;

    /* Construct Object */
    public ftp(string hostIP, string userName, string password) { host = hostIP; user = userName; pass = password; }

    private object fileFolderCheckLock = new object(); //Only check if a file/dir exists one thread at a time
    private object requestLock = new object(); //Don't create multiple ftprequests simultaneously. Exit this lock when the response is being received.

    /* Create a New Directory on the FTP Server */
    public bool CreateDirectory(string newDirectory)
    {
        FtpWebRequest ftpRequest = null;
        FtpWebResponse ftpResponse = null;
        try
        {
            lock(requestLock)
            {
                if(!newDirectory.EndsWith("/")) newDirectory += "/";
                //Console.WriteLine("chk: "+host + "/" + newDirectory);
                Uri theuri = new Uri(host + "/" + newDirectory);
                //Console.WriteLine("theuri: "+theuri.ToString());
                /* Create an FTP Request */
                ftpRequest = (FtpWebRequest)WebRequest.Create(theuri);
                /* Log in to the FTP Server with the User Name and Password Provided */
                ftpRequest.Credentials = new NetworkCredential(user, pass);
                /* When in doubt, use these options */
                ftpRequest.UseBinary = true;
                ftpRequest.UsePassive = true;
                ftpRequest.KeepAlive = true;
                ftpRequest.Timeout = 10000;
                /* Specify the Type of FTP Request */
                ftpRequest.Method = WebRequestMethods.Ftp.MakeDirectory;
                /* Establish Return Communication with the FTP Server */
                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
            }
        }
        catch (Exception ex){ Console.WriteLine("CreateDirectory Exception"+ex.ToString()); }
        finally
        {
            /* Resource Cleanup */
            try{ftpResponse.Close();}catch(Exception){}//??
            ftpRequest = null;
        }
        return true;
    }
}

有谁能告诉我为什么会这样?

1 个答案:

答案 0 :(得分:7)

您可能正在达到默认的最大连接数。看看这个:How can I programmatically remove the 2 connection limit in WebClient