當涉及到異步操作時有點小問題,但是我對ObservableCollection有些問題,並且不確定問題是因爲它是否在異步方法中。當它試圖增加其與System.AccessViolationException錯誤崩潰委託...下面的代碼:WP8 ObservableCollection.CollectionChanged委託崩潰
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方法的數據源收集被添加到,這樣的想法是,GetContacts被稱爲6次並且每次將返回數據添加到dataSource中。
當發生這種情況時,我想調用dataSource_CollectionChanged來更新XAMl頁面上綁定的longlistselector。
有人能告訴我我要去哪裏嗎?
感謝
如果你不想在每次添加項目時更新你的LLS(糾正我,如果我誤解了你) - 刪除訂閱事件,並在等待Task.WhenAll(任務)後運行更新方法; – Romasz
我試過了,但實際上並沒有等待,我更新了GetContacts方法以顯示它的功能。我認爲,因爲它也在運行異步,所以它沒有給最終等待...如果這是有道理的。 –