日期:2014-05-17 浏览次数:21076 次
WebClient中有DownloadProgressChangedEventHandler等事件可以响应http请求(或者其他web请求)的进度。
在c# 5.0中,HttpClient的函数都是以Task异步函数存在,没有事件可以回调显示上传或下载的进度。
我找了很久,终于发现ProgressMessageHandler 可以解决这个问题,链接:http://msdn.microsoft.com/en-us/library/system.net.http.handlers.progressmessagehandler(v=vs.108).aspx
具体示例代码
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);