2

我有这样的场景

while ( until toUpload list empty)
{
   create ftp folder (list.item);

   if (upload using ftp (list.item.fileName))
   {
     update Uploaded list that successfully updated;
   }
}

update database using Uploaded list;

这里我使用同步方法在这个循环中上传文件。我有一个要求优化这个上传。我发现这篇文章如何提高 FtpWebRequest 的性能?并按照他们提供的说明进行操作。因此我达到了 2000 秒到 1000 秒的时间。然后我开始使用异步上传,如 msdn 中的此示例所示。http://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest(v=vs.90).aspx。我改变了方法

if (upload using ftp (list.item.fileName)) 

if (aync upload using ftp (list.item.fileName))

但事情变得更糟了。时间变成1000s到4000s。

我必须将许多文件上传到我的 ftp 服务器。因此最好的方法应该是(猜测)异步的。有人帮助我如何以正确的方式做到这一点。我无法找到如何正确使用上面的 msdn 示例代码。

我的代码 - 同步(删除异常处理以节省空间):

public bool UploadFtpFile(string folderName, string fileName)
{     
  try
  {
    string absoluteFileName = Path.GetFileName(fileName);           

    var request = WebRequest.Create(new Uri(
      String.Format(@"ftp://{0}/{1}/{2}",
         this.FtpServer, folderName, absoluteFileName))) as FtpWebRequest;
    request.Method = WebRequestMethods.Ftp.UploadFile;
    request.UseBinary = true;
    request.UsePassive = true;
    request.KeepAlive = true;
    request.Credentials = this.GetCredentials();
    request.ConnectionGroupName = this.ConnectionGroupName; 
    request.ServicePoint.ConnectionLimit = 8; 

    using (FileStream fs = File.OpenRead(fileName))
    {
      byte[] buffer = new byte[fs.Length];
      fs.Read(buffer, 0, buffer.Length);
      fs.Close();
      using(var requestStream = request.GetRequestStream())
      {
        requestStream.Write(buffer, 0, buffer.Length);
      }
    }

    using (var response = (FtpWebResponse)request.GetResponse())
    {
        return true;
    }
  }
  catch // real code catches correct exceptions
  {
     return false;  
  }
}

异步方法

public bool UploadFtpFile(string folderName, string fileName)
{     
  try 
  {
    //this methods is exact method provide in msdn example mail method
    AsyncUploadFtp(String.Format(@"ftp://{0}/{1}/{2}", 
      this.FtpServer, folderName, Path.GetFileName(fileName)), fileName);

    return true;
  }
  catch // real code catches correct exceptions
  {
     return false;  
  }
}
4

1 回答 1

0

您是否尝试在foreach循环中使用它?

Task.Factory.StartNew(() => UploadFtpFile(folderName, filename));
于 2014-03-11T08:45:14.380 回答