WP7 - 发出异步请求/响应时丢失对象的引用

时间:2012-04-29 15:15:41

标签: windows-phone-7 asynchronous httpwebrequest httpwebresponse

我正在向服务提出请求并获得回复。服务工作正常,我正在反对一个没有问题的对象。

以下是我的代码示例。问题是结果对象在结尾处为null。我不知道为什么我会失去参考。什么是正确的解决方案?

        HttpWebRequest hwrq = (HttpWebRequest)WebRequest.Create("http://service.svc/Login");
        hwrq.ContentType = "application/x-www-form-urlencoded; encoding='utf-8'";
        hwrq.Accept = "text/xml";
        hwrq.Method = "POST";

        Users result = null; // object initializaiton

        hwrq.BeginGetRequestStream(ar =>
        {
            var requestStream = hwrq.EndGetRequestStream(ar);
            using (var sw = new StreamWriter(requestStream, System.Text.Encoding.UTF8))
            {
                sw.Write("Username Password");
                sw.Close();
            }

            hwrq.BeginGetResponse(a =>
            {
                var response = hwrq.EndGetResponse(a);
                var responseStream = response.GetResponseStream();
                using (var sr = new StreamReader(responseStream))
                {
                    returnedXML = sr.ReadToEnd();

                    XmlSerializer xds = new XmlSerializer(typeof(Users));

                    byte[] byteArray = Encoding.UTF8.GetBytes(returnedXML);
                    MemoryStream stream = new MemoryStream(byteArray);

                    result = (Users)xds.Deserialize(stream); // object is correct
                }
                responseStream.Close();
                response.Close();
            }, null);
        }, null);

        return result; // object is null!

1 个答案:

答案 0 :(得分:0)

就像MarcinJuraszek建议的那样,正确的方法是进行回调并在那里处理结果。