1

这是通过 AsyncCallback 函数处理 HttpWebRequest 的代码片段。服务器端响应良好。它只响应一条返回消息,但是这个客户端代码被多次调用,让人头疼。

// 创建请求 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;
                            }
                        }

我得到了非常连续的相同返回消息。任何人都可以帮忙吗?提前致谢。

4

1 回答 1

0

似乎问题在行

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

MSDN描述了异步请求和响应的正确实现

注意这一行:

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

希望这可以帮助。

于 2012-08-13T16:15:50.747 回答