c# HttpClient上传和下载的进度显示问题
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
补充:软件开发 , C# ,