1
votes

This is a code snippet for processing HttpWebRequest by AsyncCallback function. Server side response well. It just responds only one return message, but this client code is called multiple times and give a terrible headache.

// Create Request HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);

        try
        {
            // Make request with the following inline Asynchronous callback
            request.BeginGetResponse(new AsyncCallback((asynchronousResult) =>
                {
                    HttpWebRequest aRequest = (HttpWebRequest)asynchronousResult.AsyncState;
                    HttpWebResponse aResponse = (HttpWebResponse)aRequest.EndGetResponse(asynchronousResult);

                    using (StreamReader streamReader = new StreamReader(aResponse.GetResponseStream()))
                    {
                        // Deserialize the result
                        string jsonString = streamReader.ReadToEnd();
                        result = DeserializeToListOfObject(jsonString);

                        JavaScriptSerializer jS = new JavaScriptSerializer();
                        result = (List<object>)jS.Deserialize<List<object>>(jsonString);

                        if (result[0] is object[])
                        {
                            foreach (object message in (object[])result[0])
                            {
                                this.ReturnMessage = message;
                            }
                        }

I got the very continuous the same return messages. Anyone could help? Thanks in advance.

1
This probably has more to do with the code that follows this snippet. Don't call this code again until the response is received and you used "ReturnMessage". Consider starting a thread instead if that's a problem so you can just use GetResponse(). - Hans Passant
Thanks Hans. I solved this issue. It's not because of my asynchronous callback implementation. Just found a problem in another location. - Leonardo Redmond

1 Answers

0
votes

Seems the problem in the line

request.BeginGetResponse(new AsyncCallback((asynchronousResult) => {}

MSDN describes proper implementation of async request and response

notice the line :

IAsyncResult result=
        (IAsyncResult) myHttpWebRequest.BeginGetResponse(new AsyncCallback(RespCallback),myRequestState);

Hope this helps.