1

如何访问 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);
    }
4

1 回答 1

11

您可以为此使用 Dispatcher。

Dispatcher.BeginInvoke( () => { /* Your UI Code - ie Callback() or listbox.items.add */ } );
于 2010-12-10T23:58:59.373 回答