views:

63

answers:

2

I have a Windows Phone 7 application (Silverlight-based) that sends a web request and receives a web response. It works fine - I am using BeginGetReponse and an AsyncCallback to call EndGetResponse.

However, I need to wait for the response to be fully received, so that I can fill a collection with the data from the response.

What would be the best way to wait for the operation to complete?

+2  A: 

You should fill in your data in your callback, after you call EndGetResponse:

request.BeginGetResponse(
      asyncResult =>
      {
         var response = request.EndGetResponse(asyncResult);
         // fill in your data here
      },
      null);

If your need to fill in your data on the UI thread, you can return to UI thread like this:

var sc = System.Threading.SynchronizationContext.Current;
request.BeginGetResponse(
      asyncResult =>
      {
         var response = request.EndGetResponse(asyncResult);
         sc.Post(o => 
            {
               // fill in your data here
            }, null);
      },
      null);

http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.endgetresponse.aspx has more elaborate sample.

Mitya
+2  A: 

You can set the AllowReadStreamBuffering property of the HttpWebRequest object to true, in which case the BeginGetResponse callback will be invoked once the entire response is available.

Note that the request is processed in the background in all cases, independently of the value of AllowReadStreamBuffering. This means that request.BeginGetResponse(...) will always return immediately, and that its callback will later be invoked in another thread. As suggested by Mitya, you can then use SynchronizationContext (or Deployment.Current.Dispatcher) to update your UI.

Andréas Saudemont