zoukankan      html  css  js  c++  java
  • 用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放在队列中一个个放出来下载就可以了。再调试下就能用啦。

  • 相关阅读:
    Windows JScript 在 游览器 中运行 调试 Shell 文件系统
    autohotkey 符号链接 软连接 symbolink
    软链接 硬链接 测试
    SolidWorks 修改 基准面 标准坐标系
    手机 路径 WebDAV 映射 驱动器
    Win10上手机路径
    explorer 命令行
    单位公司 网络 封锁 屏蔽 深信 AC
    cobbler自动化部署原理篇
    Docker四种网络模式
  • 原文地址:https://www.cnblogs.com/socialdk/p/3358323.html
Copyright © 2011-2022 走看看