Unauthorizedaccessexception {“无效的跨线程访问。”} ...正在发生

时间:2011-08-24 13:25:08

标签: windows-phone-7

我想简单地缩短我的网址但是当我想将字符串设置为我的文本块时会发生异常

    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; }
}

1 个答案:

答案 0 :(得分:10)

来自HttpWebRequest的回调发生在非UI线程上。如果要在UI中更改soemthing,则必须在UI线程上执行此操作。 Fortunatley有一个简单的方法可以做到这一点。您只需使用调度程序在UI上调用有问题的代码。

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