簡體   English   中英

WP8 ObservableCollection.CollectionChanged委托崩潰

[英]WP8 ObservableCollection.CollectionChanged delegate crashing

關於異步操作,有點菜鳥問題,但是我在ObservableCollection上遇到了一些麻煩,不確定問題是否是因為它在異步方法中。 當它嘗試添加委托時,它因System.AccessViolationException錯誤而崩潰...這是代碼:

public partial class ContactsList : PhoneApplicationPage
{
    static ObservableCollection<Contact> dataSource { get; set; }

    public ContactsList()
    {
        InitializeComponent();
    }

    protected async override void OnNavigatedTo(NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);
        dataSource.CollectionChanged += this.dataSource_CollectionChanged;

        var tasks = new List<Task>();
        for (int i = 1; i < 6; i++)
        {
            tasks.Add(GetContacts(i.ToString()));
        }
        await Task.WhenAll(tasks);
    }

    private void dataSource_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        List<AlphaKeyGroup<Contact>> DataSource = AlphaKeyGroup<Contact>.CreateGroups(dataSource, System.Threading.Thread.CurrentThread.CurrentUICulture, (Contact s) => { return s.Name; }, true);
        ContactsLList.ItemsSource = DataSource;
    }


    public async Task GetContacts(string page)
    {
        try
        {
            string strCredidentials = Globals.APIKey;
            string strAuthorization = Convert.ToBase64String(Encoding.UTF8.GetBytes(strCredidentials));
            RestClient client = new RestClient(Globals.myURL);

            RestRequest request = new RestRequest("/contacts.json?state=all&page=" + page);
            request.RequestFormat = DataFormat.Json;
            request.AddHeader("Authorization", "Basic " + strAuthorization);
            request.Method = Method.GET;

            var rslt = client.ExecuteAsync(request, (r) =>
            {
                if (r.ResponseStatus == ResponseStatus.Completed)
                {
                    if (r.Content == "" || r.Content == " ")
                    {
                        MessageBox.Show("No Contacts Found");
                    }
                    else
                    {
                        dataSource = new ObservableCollection<Contact>();
                        var conts = JsonConvert.DeserializeObject<List<ContactWrapper>>(r.Content);
                        foreach (ContactWrapper cont in conts)
                        {
                            try
                            {
                                string name = cont.User.Name;
                                string email = cont.User.Email;
                                string mobile = cont.User.Mobile;
                                string phone = cont.User.Phone;
                                string jobtitle = cont.User.JobTitle;
                                dataSource.Add(new Contact("", "", "", "", "", email, "", jobtitle, mobile, name, phone, ""));
                            }
                            catch { }
                        }
                    }
                }
            });
        } catch {}
      }
    }
 }

在GetContacts方法中,將dataSource集合添加到其中,因此,想法是調用GetContacts 6次,並且每次將返回數據添加到dataSource中。

發生這種情況時,我想調用dataSource_CollectionChanged來更新XAMl頁面上綁定的longlistselector。

有人可以告訴我我要去哪里了嗎?

謝謝

基於您的代碼構建了一個簡單的示例 ,看來您的代碼還可以。

我認為問題可能出在您的Task GetContacts(string page)中的// Do stuff here -檢查是否不嘗試在UI中進行更改,請使用Dispatcher進行操作:

Deployment.Current.Dispatcher.BeginInvoke(() => 
       { 
          //do UI stuff here; 
       });

編輯 -在討論中結果表明Collection尚未在啟動時初始化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM