简体   繁体   English

异步回调函数被多次调用(C#)

[英]Asynchronous callback function is called multiple times (C#)

This is a code snippet for processing HttpWebRequest by AsyncCallback function. 这是用于通过AsyncCallback函数处理HttpWebRequest的代码段。 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); //创建请求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. 提前致谢。

Seems the problem in the line 似乎在排队的问题

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

MSDN describes proper implementation of async request and response MSDN描述了异步请求和响应的正确实现

notice the line : 注意这一行:

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

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM