我在 c# 中使用 Task 在多线程中通过 FTP 发送文件。
这是我的函数(文件是字符串列表)
Task<bool>[] result = new Task<bool>[file.Count];
int j = 0;
foreach (string f in file)
{
result[j] = new Task<bool>(() => ftp.UploadFtp(f, "C:\\Prova\\" + f + ".txt", j));
result[j].Start();
j++;
//System.Threading.Thread.Sleep(50);
}
Task.WaitAll(result, 10000);
以及上传文件的功能
public static bool UploadFtp(string uploadFileName, string localFileName, int i)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://127.0.0.1/" + uploadFileName + ".txt");
//settare il percorso per il file da uplodare
//FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://desk.txt.it/");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("ftp_admin", "");
//request.Credentials = new NetworkCredential("avio", "avio_txt");
try
{
Console.WriteLine(uploadFileName);
Console.WriteLine(i);
StreamReader sourceStream = new StreamReader(localFileName);
byte[] fileContents = File.ReadAllBytes(localFileName);
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
//MessageBox.Show("Upload File Complete, status {0}", response.StatusDescription);
response.Close();
return true;
}
catch (Exception e)
{
return false;
}
}
以这种方式,程序总是尝试保存列表的最后一个文件,但如果我添加一个 Sleep(50) 它会正确上传文件。似乎只有当我不使用睡眠时,程序才会启动 4 个任务做同样的工作(保存最后一个文件),但我不明白为什么,也不知道如何解决这个问题。
有人能帮我吗?谢谢你