开发者

Cross thread access problem in ResponseCallback in Windows Phone 7

Basically, I'm getting some data from a WebService, and in the Response开发者_运维技巧Callback I'm trying to fill an ObservableCollection with the results I got from the response, but I get an UnauthorizedAccessException "Invalid cross-thread access" when I try to do so.

What would be the best way to fill said observable collection when I get the result?

Thanks!

This is the code:

    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();
        }
    }


I have exactly same problem on WP7. It can be solved by the code Mick N suggested and with no need to inheriting from DO. Just take a Dispatcher from static Deployment class.

Deployment.Current.Dispatcher.BeginInvoke( () => { //your ui update code } );

But this seems to me kind of weird solution, I've never have to do this in desktop Silverlight.

Is this WP7 specific or is there some better solution? Thanks.


You might want to have a look at this http://codeblitz.wordpress.com/2009/05/27/handling-cross-threading-in-observablecollection/


If you want to update the UI (even indirectly via an observed collection) from another thread you just need to use the dispatcher as follows:

Dispatcher.BeginInvoke( () => { //your ui update code } );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜