好像是说W ebClient方式可以实现进度条。
如果用HttpWebRequest请求怎么加进度条?
HttpWebRequest请求如下:
HttpWebRequest httpRequest = HttpWebRequest.CreateHttp("http://www.baidu.com");
httpRequest.Method = "POST";
httpRequest.BeginGetResponse(ResponseCallBack, httpRequest);
//回调
private void ResponseCallBack(IAsyncResult asyncResult)
{
HttpWebRequest httpWebRequest = (HttpWebRequest)asyncResult.AsyncState;
HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.EndGetResponse(asyncResult);
Stream stream = httpWebResponse.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string result = reader.ReadToEnd();
Dispatcher.BeginInvoke(() =>
{
//
});
}
如果请求返回数据量大,string result这个执行时间较长,所以可否实现在这段时间显示进度条?
------解决方案--------------------
我印象这东西没有进度汇报。
------解决方案--------------------
直接弄个提示就好了- =
------解决方案--------------------
大致这么做
int count = 0;
while(int num = stream.read(bufferbyte[],1000) != -1)
{
count += num;
percent = count/length; //汇报进度
}
------解决方案--------------------
楼上是宫崎骏迷吗?呵呵,具体的说
httpRequest.BeginGetResponse(ResponseCallBack, httpRequest);
在这句之后吧进度条调起来。
再回调函数当中走进度条。
------解决方案--------------------
在下载的过程中使用Action来反馈进度,如:
Action<double> reportProcess = percent =>
{
Dispatcher.BeginInvoke(() =>
{
pb_DownLoadProgress.Value = percent;//这是进度条
});
};
具体到读数据的时候这样:
//需要报告进度
double fileLength = fs.Length;
do
{
bytesRead = await stream.ReadAsync(bytes, 0, buffer_Size);
fs.Write(bytes, 0, bytesRead);
sum += bytesRead;
double percent = sum * 1.0 / fileLength;
reportProcess(percent);//这里调用了之前的那个Action
} while (bytesRead > 0);
9楼的方法很不好,不要采用httpClient.DownloadStringAsync方法来实现下载,这样会在你读取数据的时候都会变成字符串保存在内存中,这样下载大文件的时候内存过大导致程序崩溃,建议采用字节流的方式下载,控制缓存大小。