You need to know a few things to succeed with this.
Step 0: save the documentation for .NET 4.0:
HttpWebRequest, , GetResponse() : BeginGetResponse() EndGetResponse(). .NET, " IAsyncResult". , , . :
Foo() BeginFoo(), IAsyncResult. Foo() , .BeginFoo() AsyncCallback, , , , . ( , , HttpWebRequest).EndFoo() IAsyncResult, BeginFoo() , , Foo().
, , . , " ", , , , . , , BeginFoo(), . :
InvokeRequired, . true, , .Invoke(), , .
, , WinForms, Google. , . , . progressBar1, GetWebContent() .
HttpWebRequest _request;
IAsyncResult _responseAsyncResult;
private void GetWebContent() {
_request = WebRequest.Create("http://www.google.com") as HttpWebRequest;
_responseAsyncResult = _request.BeginGetResponse(ResponseCallback, null);
}
GetResponse(). IAsyncResult , ResponseCallback() EndGetResponse(). GetWebContent() , , , . ResponseCallback():
private void ResponseCallback(object state) {
var response = _request.EndGetResponse(_responseAsyncResult) as HttpWebResponse;
long contentLength = response.ContentLength;
if (contentLength == -1) {
}
Stream responseStream = response.GetResponseStream();
GetContentWithProgressReporting(responseStream, contentLength);
response.Close();
}
object AsyncCallback, . EndGetResponse() IAsyncResult, , , . , , , - .
, , , . , , , -1. , , . - , .
, , , :
private byte[] GetContentWithProgressReporting(Stream responseStream, long contentLength) {
UpdateProgressBar(0);
var data = new byte[contentLength];
int currentIndex = 0;
int bytesReceived = 0;
var buffer = new byte[256];
do {
bytesReceived = responseStream.Read(buffer, 0, 256);
Array.Copy(buffer, 0, data, currentIndex, bytesReceived);
currentIndex += bytesReceived;
double percentage = (double)currentIndex / contentLength;
UpdateProgressBar((int)(percentage * 100));
} while (currentIndex < contentLength);
UpdateProgressBar(100);
return data;
}
( ), .
. . . , . , , . , , , .
( , : , , . Stopwatch , .)
, , , -:
private void UpdateProgressBar(int percentage) {
if (progressBar1.InvokeRequired) {
progressBar1.Invoke(new Action<int>(UpdateProgressBar), percentage);
} else {
progressBar1.Value = percentage;
}
}
InvokeRequired true, Invoke(). , . WPF, , , Dispatcher.
. , async . IAsyncResult , . , .
:
- . .
GetResponse(), EndGetResponse().- , , , . .
- , ! ,
Stream, Length, , . A Stream NotSupportedException , , -1, , , , , , , : " ?" - , :
- .
- : , ,
HttpWebRequest.BeginGetRequestStream(), . .