我無法抗拒回答這個。我認爲你不會再需要這個答案,但也許有人可以使用它。不要想太多(不要使用這個多線程(這會使事情容易出錯並且不必要的複雜,只能使用線程進行硬計算/ IO),所有這些不同的操作類型都會使緩衝變得非常困難。最煩人的部分是,如果您刪除或添加10000個項目,您的應用程序(列表框)將非常忙於處理由ObservableCollection引發的事件。此事件已支持多個項目。因此.....
您可以緩衝項目直到它改變動作爲止,所以添加動作將被緩衝,並且如果'用戶'改變動作或刷新動作,將會以批處理形式提出。 還沒有測試它,但你可以做這樣的事情:
// Written by JvanLangen
public class BufferedObservableCollection<T> : ObservableCollection<T>
{
// the last action used
public NotifyCollectionChangedAction? _lastAction = null;
// the items to be buffered
public List<T> _itemBuffer = new List<T>();
// constructor registeres on the CollectionChanged
public BufferedObservableCollection()
{
base.CollectionChanged += new NotifyCollectionChangedEventHandler(ObservableCollectionUpdate_CollectionChanged);
}
// When the collection changes, buffer the actions until the 'user' changes action or flushes it.
// This will batch add and remove actions.
private void ObservableCollectionUpdate_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
// if we have a lastaction, check if it is changed and should be flush else only change the lastaction
if (_lastAction.HasValue)
{
if (_lastAction != e.Action)
{
Flush();
_lastAction = e.Action;
}
}
else
_lastAction = e.Action;
_itemBuffer.AddRange(e.NewItems.Cast<T>());
}
// Raise the new event.
protected void RaiseCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (this.CollectionChanged != null)
CollectionChanged(sender, e);
}
// Don't forget to flush the list when your ready with your action or else the last actions will not be 'raised'
public void Flush()
{
if (_lastAction.HasValue && (_itemBuffer.Count > 0))
{
RaiseCollectionChanged(this, new NotifyCollectionChangedEventArgs(_lastAction.Value, _itemBuffer));
_itemBuffer.Clear();
_lastAction = null;
}
}
// new event
public override event NotifyCollectionChangedEventHandler CollectionChanged;
}
玩得開心!J3R03N
看到這個http://stackoverflow.com/questions/1007691/observablecollection-databinding-performance – Sauron 2009-09-09 09:32:00