Unauthorizedaccessexception{ "Invalid cross-thread access." }...是发生的



我想用bit来缩短我的url,但当我想将字符串设置为我的文本块

时,会发生异常
    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; }
}

来自HttpWebRequest的回调发生在一个非ui线程上。如果你想在UI中改变一些东西,你必须在UI线程中做。幸运的是,有一个简单的方法可以做到这一点。您只需使用分派器在UI上调用有问题的代码。

Dispatcher.BeginInvoke(() => textBox2.Text = output);

相关内容

最新更新