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