2011-08-24 52 views
0

我想我的短網址與bitly但是當我想列出的字符串我的文字塊發生異常Unauthorizedaccessexception {「無效的跨線程訪問。」} ...是發生

private void button1_Click(object sender, RoutedEventArgs e) 
    { 
     ShortenUrl(textBox1.Text); 
    } 
    enum Format 
    { 
     XML, 
     JSON, 
     TXT 
    } 

    enum Domain 
    { 
     BITLY, 
     JMP 
    } 

    void ShortenUrl(string longURL) 
    { 
     Format format = Format.XML; 
    Domain domain = Domain.BITLY; 
     string _domain; 
     //string output; 

     // Build the domain string depending on the selected domain type 
     if (domain == Domain.BITLY) 
      _domain = "bit.ly"; 
     else 
      _domain = "j.mp"; 

     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(
      string.Format(@"http://api.bit.ly/v3/shorten?login={0}&apiKey={1}&longUrl={2}&format={3}&domain={4}", 
      "username", "appkey", HttpUtility.UrlEncode(longURL), format.ToString().ToLower(), _domain)); 

     request.BeginGetResponse(new AsyncCallback(GetResponse), request); 

    } 
    void GetResponse(IAsyncResult result) 
    { 
     XDocument doc; 
     HttpWebRequest request = (HttpWebRequest)result.AsyncState; 
     HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(result); 

      using (StreamReader reader = new StreamReader(response.GetResponseStream())) 
      { 
       string responseString = reader.ReadToEnd(); 
       doc = XDocument.Load(reader.BaseStream); 
      } 

      //// var x = from c in doc.Root.Element("data").Elements() 
      //   where c.Name == "url" 
      //   select c; 

      //XElement n = ((IEnumerable<XElement>)x).ElementAt(0); 
      // textBox2.Text = ((IEnumerable<String>)x).ElementAt(0); 

      lista = (from Born_rich in doc.Descendants("url") 

        select new a() 
        { 
         shrtenurl = Born_rich.Value 
        }).ToList(); 
      output = lista.ElementAt(0).shrtenurl; 
      textBox2.Text = output; 

     // 
       // 


    //  textBox2.Text = s; 
    } 
    List<a> lista = new List<a>(); 



    String output; 
} 
public class a 
{ 
    public String shrtenurl { set; get; } 
} 

回答

10

來自HttpWebRequest的回調在非UI線程上發生。如果你想改變UI中的東西,你必須在UI線程上做。 Fortunatley有一個簡單的方法來做到這一點。您只需使用調度程序在UI上調用有問題的代碼。

Dispatcher.BeginInvoke(() => textBox2.Text = output); 
相關問題