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;
的情景在這裏,我使用的同步方法來上傳文件,在這個循環中。我有一個要求優化這個上傳。我發現這篇文章How to improve the Performance of 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;
}
}
10s意味着什麼都不幸...您期望的速度(即文件大小/最大上傳速度)是多少?你知道你現在是否能發送比現在更多的數據? (也可以在你的代碼中得到一些合理的建議,你需要展示至少看起來像C#代碼的樣本)。 – 2013-02-14 06:31:06
我將我的代碼添加到了問題中,您是否知道如果您現在可以發送比您現在要做的更多的數據?我減少20秒到10秒,上面的例子說他用異步方法減少到5秒。在一般的環境中,我將能夠以同樣的原因獲得第一個成就。請給我一些建議。 – cdev 2013-02-14 08:17:52
建議1:在發佈代碼時儘可能小和儘可能有用 - 也就是說,您已經發布了單個文件的同步上傳代碼,沒有迭代代碼和異步版本(最常見的問題是異步速度較慢)。建議2:獨立於代碼測量最大上傳速度。建議3:設定你的目標 - 「10s很慢」不是一個,像「最多1000個文件的最大組合大小1TB應該在3秒內上傳」可能是。建議4:剖析你的代碼。 – 2013-02-14 16:32:12