2012-05-18 75 views
0

我有以下代碼似乎拋出「無效的跨線程訪問」。我似乎無法弄清楚爲什麼。我正在從URL加載遠程XML文件,但是,解析XML時,我總是收到此錯誤。有什麼建議麼?C#Windows Phone芒果 - 無效的跨線程訪問?解析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> 
+0

-1您是否嘗試過谷歌錯誤'無效的跨線程訪問?重複數十億的類似問題 –

+0

我確實看到了許多其他錯誤,但是,我需要進一步澄清,這是Mayank提供的。 – Euthyphro

回答

5

textBox1.Text = output.ToString(); //無效的跨線程訪問。

你得到的是因爲你正在對IO線程進行操作時調用UI線程。嘗試分離這些操作或在UI線程上調用invoke

嘗試將您的代碼更改爲像這樣的東西。

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

謝謝,這正是我所需要的。 – Euthyphro

3

從Mayank添加一些細節:

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

你當元帥的呼叫UI對象退回到UI線程。沒有任何東西可以修改任何其他線程上的UI元素,而非主線程。

+0

謝謝彼得:) – Mayank