c# - C#Windows Phone Mango-无效的跨线程访问?解析XML

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

我有以下代码似乎抛出了“无效的跨线程访问”。而且我似乎不知道为什么。我正在从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>

最佳答案

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

之所以会这样,是因为您在IO线程上执行操作时正在调用UI线程。尝试分离这些操作或在UI线程上调用invoke

尝试将您的代码更改为此类。

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

关于c# - C#Windows Phone Mango-无效的跨线程访问?解析XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10660779/

相关文章:

java - hadoop map reduce程序中的InstantiationException

C# 从返回 char 指针的 c++ 函数中获取字符串/字符值

xml - 在Scala中评估Xpath

c# - SQL Server CE 抛出不兼容异常

java - 我如何更改 ListView 中文本的大小?

c# - 在 Windows Phone 7 中画线?

windows-phone-7 - 如何在 Windows Phone 7 中创建确认对话框?

windows-phone-7 - 如何获取从互联网下载的图像的来源?

c# - 如何仅保存图片框中显示的图像

c# - EntityFramework 包版本 ="6.1.3"和 Web 配置版本 6.0.0.0?