ObservableCollection and Multi-Threading

These days I was looking for a synchronized implementation of ObservableCollection<T>, i.e. to generate notifications in the same thread that created the collection. Unfortunately .NET 3.0 doesn’t provide one, and there are only a few Internet blog entries with some sample code and discussions.
 
However, after reviewing the existing sample code both from public blogs and from MSDN (usually the examples used the WPF Dispatcher object, which is fine for WPF only components, but I needed my collection to work also outside WPF), I reached out to this simple implementation (although possibly, not the most optimal). Anyway it works not only in WPF or UI, but also wherever you may need threading synchronization for the collection notifications (I hope it helps someone):
 

public

class MyCollection<T> : ObservableCollection<T>

{

  private SynchronizationContext dispatcher = SynchronizationContext.Current;

  protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)

  {
    dispatcher.Post((

SendOrPostCallback)delegate { base.OnCollectionChanged((NotifyCollectionChangedEventArgs)e); }, e);

  }

  protected override void OnPropertyChanged(PropertyChangedEventArgs e)

  {
    dispatcher.Post((

SendOrPostCallback)delegate { base.OnPropertyChanged((PropertyChangedEventArgs)e); }, e);

  }
}

About Sorin Dolha

My passion is software development, but I also like physics.
This entry was posted in Computers and Internet. Bookmark the permalink.

Add a reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s