开发者

Populating a WP7 List from a webservice causes 'Invalid cross-thread access.'

开发者 https://www.devze.com 2023-03-06 04:05 出处:网络
Sorry if this is a easy question but I am totally new to WP7. I have a rest service that I am trying to consume however I get an error \'Invalid cross-thread access.\'

Sorry if this is a easy question but I am totally new to WP7. I have a rest service that I am trying to consume however I get an error 'Invalid cross-thread access.'

This is my code

   public ObservableCollection<TransactionViewModel> Transactions { get;private set; }
   public MainViewModel()
    {
        this.Transactions = new ObservableCollection<TransactionViewModel>();
    }
    public void LoadTransactions(string id)
    {
        var req = (HttpWebRequest)WebRequest.Create(string.Format("http://domain.com/Transactions?Id={0}", id));
            req.Method = "POST";
            req.ContentType = "application/json; charset=utf-8";

           // call async
            req.BeginGetResponse(new AsyncCallback(jsonGetRequestStreamCallback), req);


        this.IsDataLoaded = true;

    }

    void jsonGetRequestStreamCallback(IAsyncResult asynchronousResult)
    {

        WebResponse response = ((HttpWebRequest)asynchronousResult.AsyncState).EndGetResponse(asynchronousResult);
        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
        {
            string responseString = reader.ReadToEnd();
            reader.Close();


            var s = JsonConvert.DeserializeObject<List<TransactionViewModel>>(responseString);

            foreach (var t in s)
            {
                Transactions.Add(new TransactionViewModel()
                                 开发者_运维问答    {
                                      .........
                                     }
            }

Have I done something really stupid here?


When you come back from the request you are no longer on the UI thread. So you need to switch control back to the UI thread before performing any actions that will affect the UI.

You are updating an ObservableCollection, which will be bound on the UI and therefore the update is going to affect the UI.

There are a number of approaches, the simplest for you purposes will be

Deployment.Current.Dispatcher.BeginInvoke(()=> {
 foreach (var t in s) {
  Transactions.Add(new TransactionViewModel());
 }
});

Edit: Also if you want to read a little more about this, I have a blog post about it here http://csainty.blogspot.com/2010/10/windows-phone-7asynchronous-programming.html it starts from code like yours that looks reasonable and should work, explains a few of the gotchas and how to get it working.

0

精彩评论

暂无评论...
验证码 换一张
取 消