程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> c# HttpClient上傳和下載的進度顯示問題

c# HttpClient上傳和下載的進度顯示問題

編輯:C#入門知識

WebClient中有DownloadProgressChangedEventHandler等事件可以響應http請求(或者其他web請求)的進度。
在c# 5.0中,HttpClient的函數都是以Task異步函數存在,沒有事件可以回調顯示上傳或下載的進度。
我找了很久,終於發現ProgressMessageHandler 可以解決這個問題,
具體示例代碼
               HttpClientHandler hand = new HttpClientHandler();
                ProgressMessageHandler processMessageHander = new ProgressMessageHandler(hand);
                HttpClient localHttpClient = new HttpClient(processMessageHander);

                HttpRequestMessage httpRequestMessage = new HttpRequestMessage();

                httpRequestMessage.Method = HttpMethod.Put;
                httpRequestMessage.Content = new StreamContent(content);

                //for upload

                processMessageHander.HttpSendProgress += (sender, e) =>
                {
                    int num = e.ProgressPercentage;     //you can use HttpProgressEventArgs e


                };

                //for download

               // processMessageHander.HttpReceiveProgress += (sender, e) =>
              //   {
               //      int num = e.ProgressPercentage;

              //   };

                HttpResponseMessage test = await localHttpClient.SendAsync(httpRequestMessage);

                // dispose the resource

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved