【问题标题】:C# Windows Phone Mango - Invalid cross-thread access? parsing XMLC# Windows Phone Mango - 无效的跨线程访问?解析 XML
【发布时间】:2012-05-26 12:13:01
【问题描述】:

我有以下代码,它似乎引发了“无效的跨线程访问”。我似乎无法弄清楚为什么。我正在从 URL 加载远程 xml 文件,但是,在解析该 XML 时,我总是收到此错误。有什么建议吗?

using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
        {
            string xml = streamReader.ReadToEnd();

            using (XmlReader reader = XmlReader.Create(new StringReader(xml)))
            {

                    reader.ReadToFollowing("channel");
                    reader.MoveToFirstAttribute();

                    reader.ReadToFollowing("title");
                    output.AppendLine("Title: " + reader.ReadElementContentAsString());

                    reader.ReadToFollowing("description");
                    output.AppendLine("Desc: " + reader.ReadElementContentAsString());

                    textBox1.Text = output.ToString(); //Invalid cross-thread access.
            }

        }

我尝试解析的 XML 如下所示,我只是在尝试解析点点滴滴,因为我继续学习如何使用 c# 解析不同类型的 XML:

<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"xmlns:dc="http://purl.org   /dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0  /modules/slash/">
  <channel>
<title>Server &amp; Site News</title>
<description>A place for the Admin and Moderators to post the latest news on both the server and site.</description>
<pubDate>Fri, 18 May 2012 22:45:08 +0000</pubDate>
<lastBuildDate>Fri, 18 May 2012 22:45:08 +0000</lastBuildDate>
<generator>Forums</generator>
<link>http://removedurl.com/forums/server-site-news.23/</link>
<atom:link rel="self" type="application/rss+xml" href="http://removedurl.com/forums/server-site-news.23/index.rss"/>
<item>
  <title>Example Title</title>
  <pubDate>Mon, 14 May 2012 17:39:45 +0000</pubDate>
  <link>http://removedurl.com/threads/back-fully-working.11013/</link>
  <guid>http://removedurl.com/threadsback-fully-working.11013/</guid>
  <author>Admin</author>
  <dc:creator>Admin</dc:creator>
  <slash:comments>14</slash:comments>
</item>
</channel>

【问题讨论】:

  • -1 你试过用谷歌搜索你的错误Invalid cross-thread access 吗?数十亿个类似问题的重复
  • 我确实看到了许多其他错误,但是,我需要进一步澄清,Mayank 提供了。

标签: c# xml windows-phone-7 url error-handling


【解决方案1】:

textBox1.Text = output.ToString(); //无效的跨线程访问。

你得到这个是因为你在 IO 线程上执行操作时调用了 UI 线程。尝试分离这些操作或在 UI 线程上调用 invoke

尝试将您的代码更改为类似的内容。

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

【讨论】:

  • 谢谢,这正是我所需要的。
【解决方案2】:

从 Mayank 添加更多细节:

Dispatcher.BeginInvoke( () => {
  textBox1.Text = output.ToString()
} );

您必须将对 UI 对象的调用编组回 UI 线程。除了主线程之外,没有任何东西可以修改任何其他线程上的 UI 元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多