I have a class that goes and grabs some data and returns it as a string. While this object is working there is a spinning icon letting the user know work is being done. The problem is the code exits before the response comes back. I stuck a
while(response == null)
In just to see whats going on and the
response = (HttpWebResponse)request.EndGetResponse(AsyncResult);
is not firing. It fires ok in a console application so I am putting this down to something I am doing that silverlight doesn’t like, heres the full code:
public class HttpWorker
{
private HttpWebRequest request;
private HttpWebResponse response;
private string responseAsString;
private string url;
public HttpWorker()
{
}
public string ReadFromUrl(string Url)
{
url = Url;
request = (HttpWebRequest)WebRequest.Create(url);
request.CookieContainer = new CookieContainer();
request.AllowAutoRedirect = true;
request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6";
AsyncRequest(); // The Demon!
return responseAsString;
}
private void AsyncRequest()
{
request.BeginGetResponse(new AsyncCallback(FinaliseAsyncRequest), null);
}
private void FinaliseAsyncRequest(IAsyncResult AsyncResult)
{
response = (HttpWebResponse)request.EndGetResponse(AsyncResult);
if (response.StatusCode == HttpStatusCode.OK)
{
// Create the stream, encoder and reader.
Stream responseStream = response.GetResponseStream();
Encoding streamEncoder = Encoding.UTF8;
StreamReader responseReader = new StreamReader(responseStream, streamEncoder);
responseAsString = responseReader.ReadToEnd();
}
else
{
throw new Exception(String.Format("Response Not Valid {0}", response.StatusCode));
}
}
}
Are you going into the busy loop with
(while response == null)on the UI thread? The async callback for theHttpRequestwill be delivered on the UI thread, so if you’re looping on that same thread, the callback can never run. You need to return to allow the main message loop to run, and then your async callback will be delivered.Your design above suggests that what you really want is a synchronous fetch anyway. Forget the callback and just call
FinaliseAsyncRequestinsideReadFromUrlyourself. The UI will hang until the request completes, but it sounds like that’s what you want.