public void DownloadStringAsync(Uri address, DownloadStringAsync_Completed callback) { CacheCalls++; // lookup address in cache Stream cachedResult = CacheLookup(address); if (cachedResult != null) { CacheHits++; CacheDownloadStringCompletedEventArgs eventArgs = new CacheDownloadStringCompletedEventArgs(new StreamReader(cachedResult), address); // Invoke on a different thread. Otherwise we make the callback from the same thread as the // original call and wierd things could happen. Thread thread = new Thread(() => callback(this, eventArgs)); thread.Start(); } else { CacheMisses++; // not found, request data HttpWebRequest requestGetter = (HttpWebRequest)HttpWebRequest.Create(address); requestGetter.BeginGetResponse( new AsyncCallback(new CacheCallback(this, callback, address).Callback), requestGetter); } }
public void Callback(IAsyncResult asyncResult) { CacheDownloadStringCompletedEventArgs newArgs; try { HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState; HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult); string statusDescr = response.StatusDescription; long totalBytes = response.ContentLength; if (response.StatusCode != HttpStatusCode.OK) { throw new WebserviceResponseException(response.StatusCode, request.RequestUri.ToString(), response.ToString(), null); } Stream s = response.GetResponseStream(); // no errors -- add data to the cache TextReader result = owner.CacheAddResult(requestedAddress, s); newArgs = new CacheDownloadStringCompletedEventArgs(result, requestedAddress); } catch (Exception e) { // TODO: Web exceptions will be caught here, and we just pass up // that exception instead of recasting it to a WebserviceResponseException(). // This will result in the loss of the RequestUrl. Debug.Assert(false); newArgs = new CacheDownloadStringCompletedEventArgs(e, requestedAddress); } callback(this, newArgs); }