A WP7 Application Never Quits BeginGetResponse and Passes a Callback Function

I have the following code:

private void GetRequestStreamCallback(IAsyncResult asynchronousResult) { HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState; // End the operation Stream postStream = request.EndGetRequestStream(asynchronousResult); //Console.WriteLine("Please enter the input data to be posted:"); //string postData = Console.ReadLine(); string postData = "my data"; // Convert the string into a byte array. byte[] byteArray = Encoding.UTF8.GetBytes(postData); // Write to the request stream. postStream.Write(byteArray, 0, postData.Length); postStream.Close(); // Start the asynchronous operation to get the response IAsyncResult result = (IAsyncResult)request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request); } private void GetResponseCallback(IAsyncResult asynchronousResult) { HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState; // End the operation HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult); Stream streamResponse = response.GetResponseStream(); StreamReader streamRead = new StreamReader(streamResponse); string responseString = streamRead.ReadToEnd(); Console.WriteLine(responseString); // Close the stream object streamResponse.Close(); streamRead.Close(); // Release the HttpWebResponse response.Close(); allDone.Set(); Dispatcher.BeginInvoke((Action)(() => Debug.WriteLine("George"))); } 

However, when my code hits the BeginGetResponse, it never exits (and I don't hit the breakpoint in the GetResponseCallback function). I tried adding a BeginInvoke call, but I still do not enter this method. This code works in the Windows console application - on Windows Phone 7, that it does not work

Can anyone see what I'm doing wrong?

Thanks.

+6
c # windows-phone-7
source share
2 answers

If you created the HttpWebRequest in the user interface thread, make sure that you are not blocking the user interface thread, otherwise you might block it.

The sample from your .NET.NET computer is not optimized for the current network network stack. You must modify the code to create an HttpWebRequest in the background thread.

+8
source share

I don’t see what is wrong with your code (maybe a complete example of what you are trying to do can help), but here is a simple working example of how to perform the action you want to do.
It sends some data to the URI and then passes the response to the callback function:

Just do it (using BackgroundWorker is optional, but recommended)

 var bw = new BackgroundWorker(); bw.DoWork += (o, args) => PostDataToWebService("http://example.com/something", "key=value&key2=value2", MyCallback); bw.RunWorkerAsync(); 

Here's the callback function to which it refers:
(You can change this, but it fits your needs.)

 public static void MyCallback(string aString, Exception e) { Deployment.Current.Dispatcher.BeginInvoke(() => { if (e == null) { // aString is the response from the web server MessageBox.Show(aString, "success", MessageBoxButton.OK); } else { MessageBox.Show(e.Message, "error", MessageBoxButton.OK); } }); } 

Here is the actual method:

 public void PostDataToWebService(string url, string data, Action<string, Exception> callback) { if (callback == null) { throw new Exception("callback may not be null"); } try { var uri = new Uri(url, UriKind.Absolute); var req = HttpWebRequest.CreateHttp(uri); req.ContentType = "application/x-www-form-urlencoded"; req.Method = "POST"; AsyncCallback GetTheResponse = ar => { try { var result = ar.GetResponseAsString(); callback(result, null); } catch (Exception ex) { callback(null, ex); } }; AsyncCallback SetTheBodyOfTheRequest = ar => { var request = ar.SetRequestBody(data); request.BeginGetResponse(GetTheResponse, request); }; req.BeginGetRequestStream(SetTheBodyOfTheRequest, req); } catch (Exception ex) { callback(null, ex); } } 

and extension / helper methods are used here:

 public static class IAsyncResultExtensions { public static string GetResponseAsString(this IAsyncResult asyncResult) { string responseString; var request = (HttpWebRequest)asyncResult.AsyncState; using (var resp = (HttpWebResponse)request.EndGetResponse(asyncResult)) { using (var streamResponse = resp.GetResponseStream()) { using (var streamRead = new StreamReader(streamResponse)) { responseString = streamRead.ReadToEnd(); } } } return responseString; } public static HttpWebRequest SetRequestBody(this IAsyncResult asyncResult, string body) { var request = (HttpWebRequest)asyncResult.AsyncState; using (var postStream = request.EndGetRequestStream(asyncResult)) { using (var memStream = new MemoryStream()) { var content = body; var bytes = System.Text.Encoding.UTF8.GetBytes(content); memStream.Write(bytes, 0, bytes.Length); memStream.Position = 0; var tempBuffer = new byte[memStream.Length]; memStream.Read(tempBuffer, 0, tempBuffer.Length); postStream.Write(tempBuffer, 0, tempBuffer.Length); } } return request; } } 
+3
source share

All Articles