Windows Phone 7中的跨线程访问无效?

时间:2012-05-25 09:39:55

标签: windows-phone-7

void GetResponseCallback(IAsyncResult asynchronousResult)
        {

            try
            {
                HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
                Stream streamResponse = response.GetResponseStream();
                StreamReader streamRead = new StreamReader(streamResponse);
                string responseString = streamRead.ReadToEnd();

                XmlReader xmlDoc = XmlReader.Create(new MemoryStream(System.Text.UTF8Encoding.UTF8.GetBytes(responseString)));

                while (xmlDoc.Read())
                {
                    if (xmlDoc.NodeType == XmlNodeType.Element)
                    {

                        if (xmlDoc.Name.Equals("ResponseCode"))
                        {
                            responseCode = xmlDoc.ReadInnerXml();

                        }

                    }

                }
                if (Convert.ToInt32(responseCode) == 200)
                {

                   MessageBox.Show("Success");
                }


                // Close the stream object
                streamResponse.Close();
                streamRead.Close();
                // Release the HttpWebResponse
                response.Close();


            }
            catch (WebException e)
            {
                // Error treatment
                // ...
            }
        }

在上面的代码中,Messagebox.show显示“无效的跨线程访问”。请告诉我如何解决这个问题......

2 个答案:

答案 0 :(得分:8)

    Dispatcher.BeginInvoke(() =>
            MessageBox.Show("Your message")
    );

答案 1 :(得分:6)

来自代码的UI的任何交互都需要在调度程序线程上,来自HTTP请求的回调将不会在此线程上运行,因此会出错。

您应该可以使用类似

的内容

Deployment.Current.Dispatcher.BeginInvoke(()=> MessageBox.SHow(“Success”));

显示消息框

HTH - 鲁珀特。