WP7 - accessing UI thread?

风流意气都作罢 提交于 2019-12-11 07:32:40

问题


How do I access the UI thread of a WP7 application?
I am using the following code, if it helps.


    private void LayoutRoot_Loaded(object sender, RoutedEventArgs e)
    {
        AcquireNews(l => { listBox1.Items.Add(l[0]); });
        // Here is where I get an exception saying "Invalid cross-thread access."
    }

    void AcquireNews(Action<List<object>> callback)
    {
        var r = HttpWebRequest.Create("http://www.google.com") as HttpWebRequest;

        r.BeginGetResponse(result =>
            {
                var response = r.EndGetResponse(result);

                List<object> l = new List<object>();

                var s = response.GetResponseStream();

                var buffer = new byte[s.Length];

                s.Read(buffer, 0, (int)s.Length);

                l.Add(System.Text.Encoding.UTF8.GetString(buffer, 0, buffer.Length));

                callback(l);
            },
        null);
    }

回答1:


You can use the Dispatcher for this.

Dispatcher.BeginInvoke( () => { /* Your UI Code - ie Callback() or listbox.items.add */ } );


来源:https://stackoverflow.com/questions/4414312/wp7-accessing-ui-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!