WP7 Propogate exception from BeginGetResponse callback

I am using HttpWebRequest to call a web service. If the AsyncCallback from BeginGetResponse causes an error, I want to decompose it to my main program stream. I am having trouble with this because the error does not extend beyond AsyncCallback. I tried putting try / catch blocks at every step of the HttpWebRequest chain, but it never extends beyond the ResponseCallBack method. Is it possible to return it to the main thread?

private void StartRequest() { // Code to create request object is here // ... httpRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), httpRequest); } 

 private void GetRequestStreamCallback(IAsyncResult result) { HttpWebRequest request = (HttpWebRequest)result.AsyncState; // End the operation var postStream = request.EndGetRequestStream(result); string body = GenerateRequestBody(); // Convert the string into a byte array byte[] postBytes = Encoding.UTF8.GetBytes(body); // Write to request stream postStream.Write(postBytes, 0, postBytes.Length); postStream.Close(); // Start the asynchronous operation to get the resonse try { request.BeginGetResponse(new AsyncCallback(ResponseCallback), request); } catch (Exception) { throw; } } 

 private void ResponseCallback(IAsyncResult result) { string contents = String.Empty; HttpWebRequest request = (HttpWebRequest)result.AsyncState; HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result); using (Stream stream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(stream)) { contents = reader.ReadToEnd(); } // Check the status if (response.StatusCode == HttpStatusCode.OK) { //EXCEPTION NEVER MAKES IT PASSED HERE, EVEN IF I HAVE IT IN A TRY/CATCH BLOCK AND RE-THROW IT. _object = ProcessResponseEntity(contents); } } 
+4
source share
1 answer

I think you're confused about how asynchronous code exploitation works and how callback execution fits the calling code.

Inside GetRequestStreamCallback after calling request.BeginGetResponse method will continue to execute and will simply end in your example.

It is not known when (or even if) the ResponseCallback will execute or what will happen in the user interface thread when this happens. Because of this, ResponseCallback will be executed in another thread.

It is possible to use code in a callback in a user interface thread (with which you will need to interact with the user interface) using Dispatcher.BeginInvoke . However, you cannot do this in the context of another method.

Although I would not recommend it, you can take a look at this discussion to make the callback execute synchronously. This will block your UI thread, although not recommended.

+2
source

All Articles