WP7 - 访问UI线程?

时间:2010-12-10 23:54:54

标签: multithreading asynchronous windows-phone-7 ui-thread

如何访问WP7应用程序的UI线程? 我使用以下代码,如果它有帮助。


    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 个答案:

答案 0 :(得分:11)

您可以使用Dispatcher。

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