ObservableCollection<T>
通常不能從後臺線程更新。您需要使用Dispatcher.Invoke()
或Dispatcher.BeginInvoke()
以確保數據添加到集合所屬的線程中。
Application.Current.Dispatcher.Invoke((Action)(() => myObservableCollection.Add(value)));
這是一個相當常見的任務,這是值得創建一個擴展方法來照顧這對你:
static class ObservableCollectionExtensions
{
internal static void InvokeAdd<T>(this ObservableCollection<T> self, T item)
{
Application.Current.Dispatcher.Invoke((Action<T>)self.Add, item);
}
internal static void BeginInvokeAdd<T>(this ObservableCollection<T> self, T item)
{
Application.Current.Dispatcher.BeginInvoke(new Action<T>(self.Add), item);
}
}
這樣你可以安全的幾個按鍵,然後輸入這個:
myObservableCollection.InvokeAdd(value);
你指的是什麼技術中的視圖和視圖模型? ASP.NET MVC? – StriplingWarrior
鎖定關鍵字不會有幫助嗎? http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx – rskar
帶有WPF的MVVM。我認爲這是因爲將ObservableCollection綁定到我的視圖 – Stephen