0

我有:

 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 并每次发送一个文件?

4

1 回答 1

1

如果您一次只能发送 1 个文件,那么您为什么要担心使用 Async?您似乎还使用后台工作人员来完成所有工作。

为每个要上传的文件启动一个“任务”,然后使用一次只允许一个任务的调度程序启动它们,难道不是更好吗?

请参阅:http: //msdn.microsoft.com/en-us/library/ee789351.aspx

这样,您可以在简化任务的同时使用一些更新的 Task 和 async 方法。


如果您想异步运行它们但一次只执行一个,则基于进一步分析:

    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.
        }
    }

它需要扩展,并且类并不都是正确的,因为我刚刚把它放在一起,但它应该提供足够的材料来引导你朝着这个方向前进。

于 2013-04-04T17:34:29.957 回答