基本上,我从Web服务中获取一些数据,并且在ResponseCallback中,我尝试使用从响应中获得的结果填充ObservableCollection,但是当我尝试执行此操作时,我得到的UnauthorizedAccessException为“无效的跨线程访问”所以。

当我得到结果时,填充所述可观察集合的最佳方法是什么?

谢谢!

这是代码:

    public ObservableCollection<Person> People { get; set; }

    private void ResponseCallback(IAsyncResult asyncResult)
    {
        HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
        HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);

        string responseString = string.Empty;

        using (Stream content = response.GetResponseStream())
        {
            if (request != null && response != null)
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    XDocument document = XDocument.Load(content);

                    var people = from p in document.Descendants()
                            where p.Name.LocalName == "PersonInfo"
                            select Person.GetPersonFromXElement(p);

                    foreach (Person person in people)
                    {
                        this.People.Add(person); // this line throws the exception
                    }
                }
            }

            content.Close();
        }
    }

最佳答案

您可能想看看这个http://codeblitz.wordpress.com/2009/05/27/handling-cross-threading-in-observablecollection/

关于c# - Windows Phone 7中ResponseCallback中的跨线程访问问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4028223/

10-12 03:03