用WebClient在异步下载或上传时每次只进行一个任务 C#

当在每次上传或者下载的时候,我只想进行一个任务的,我用的是WebClient类,但是我又不想用同步的方法UploadFile、DownloadFile,因为WebClient这个类的同步方法没有UploadProgressChanged、UploadFileCompleted这两个事件,这样就不能简单的设置进度条啦。所以还是应该在异步事件中把他当做成同步的做咯,所以要用Queue这个东西,放进队列,然后一个一个的再放出来,方法嘛如下所示(以上传为例):

    private Queue<string> filePaths = new Queue<string>();
    WebClient myWebClient = null;

    private void upload(List<string> someFilesPath){
      foreach (var each in someFilesPath)
          {
              filePaths.Enqueue(each);
          }
        Upload();
    }

    private void Upload() {
            string url = "url...";
            if (filePaths.Any()) {
                myWebClient = new WebClient();
                myWebClient.UploadProgressChanged += MyWebClient_UploadProgressChanged;
                myWebClient.UploadFileCompleted += MyWebClient_UploadFileCompleted;
                var filePath = filePaths.Dequeue();
                myWebClient.UploadFileAsync(new Uri(url), "Post", filePath);
            }
        }

        void MyWebClient_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e) {
            double bytes = e.BytesSent;
            double totalBytes = e.TotalBytesToSend;
            double percentage = bytes * 100 / totalBytes;
            progressBar.Value = percentage;
            label.Content = string.Format("完成进度: {0}%", ((int)progressBar.Value).ToString());
        }

        void MyWebClient_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e) {
            if (e.Error != null) {
                this.label.Content = e.Error.Message;
            }
            if (e.Cancelled) {

            }
            myWebClient.Dispose();
            Upload();
        }

 大致么就是这个样子的,下载也是差不多的,把下载的URL放在队列中一个个放出来下载就可以了。再调试下就能用啦。

原文地址:https://www.cnblogs.com/socialdk/p/3358323.html