私はこのようなシナリオを持っています
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))
しかし、事態は悪化しました。時間は1000秒から4000秒になります。
多くのファイルを 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;
}
}