我有:
foreach (FileInfo fileinfo in Arquivos)
{
float zz = (float)fileinfo.Length;
zz = (zz / 1024f) / 1024f;
label8.Text = "sending: " + fileinfo.Name + "("+zz.ToString("0.0")+"MB)...";
label8.Update();
WebClient client = new System.Net.WebClient();
client.Credentials = new System.Net.NetworkCredential(usuario, senha);
client.UploadProgressChanged += new UploadProgressChangedEventHandler(UploadProgressCallback);
client.UploadFile(new Uri("ftp://" + ftp + "/" + caminho + "//" + fileinfo.Name), "STOR", pasta + mes + fileinfo.Name);
bar++;
backgroundWorker1.ReportProgress(bar);
}
我需要创建一个UploadProgressChanged,所以我有:
client.UploadProgressChanged += new UploadProgressChangedEventHandler(UploadProgressCallback);
和
private void UploadProgressCallback(object sender, UploadProgressChangedEventArgs e)
{
progressBar2.Value = e.ProgressPercentage;
progressBar2.Update();
}
UploadProgressChanged不适用于UploadFile,只是UploadfileAsync,但我每次都需要发送1个文件。如何将UploadFile更改为UploadFileAsync并每次发送一个文件?
答案 0 :(得分:1)
如果您一次只能发送1个文件,那么为什么还要关注使用Async?您似乎也在使用后台工作人员来完成所有工作。
你是不是最好为每个要上传的文件启动'任务',并使用一次只允许一个任务的调度程序将它们踢掉?
请参阅:http://msdn.microsoft.com/en-us/library/ee789351.aspx
通过这种方式,您可以在简化任务的同时使用一些较新的Task和异步方法。
基于进一步分析,如果您想异步运行它们,但一次只能执行一次:
private AutoResetEvent _fileUploadedEvent = new AutoResetEvent(false);
private void DoUploadBackgroundWorker()
{
foreach (var file in files)
{
client.WhenUploaded += (s, e) =>
{
// This signals the AutoResetEvent that it can continue
_fileUploadedEvent.Set();
};
client.UploadAsync();
// This will keep ticking over every 15 milliseconds to check if the
// AutoResetEvent has been triggered
while (_fileUploadedEvent.WaitOne(15)) { }
// We get here when it's been triggered (which means the file was uploaded)
// So we can update the progressbar here and then move onto the next file.
}
}
它需要扩展,并且这些类并不完全正确,因为我刚刚将它们组合在一起,但它应该提供足够的材料来启动你的方向。