Click here to Skip to main content
15,867,453 members
Articles / Programming Languages / C#
Tip/Trick

Concurrent Observable Collection

Rate me:
Please Sign up or sign in to vote.
4.42/5 (10 votes)
11 Apr 2012CPOL2 min read 57.2K   23   19
Using ObservableCollection in a multi-threaded environment.

Introduction

There are plenty of custom implementations of thread safe observable collections. Some are more advanced than others but in most scenarios these are overkill. The overhead introduced by concurrency code in most cases is not necessary. I will demonstrate how the regular ObservableCollection could be used in a multithreaded environment without any need for creating a new type.

Background

In order to use a collection in a thread safe manner, at the very least, there has to be an object which could be used to synchronize access to the collection. Most custom solutions subclass the ObservableCollection in order to associate a sync object with the collection but it is not necessary. ObservableCollection already has that object. It derives from the Collection class which implements the ICollection interface.

C#
public interface ICollection : IEnumerable
{
    int Count { get; }
    bool IsSynchronized { get; }
    object SyncRoot { get; }
    void CopyTo(Array array, int index);
}

The SyncRoot property gives us exactly the object we need. Now synchronization of the collection is only a matter of properly applying locks only where and when it is required. There is no point in wasting any processing time where it is not needed.

Using the code

Using the collections in a thread safe manner is very simple. Just cast it into ICollection and lock on the SyncRoot property:

C#
lock ((_collection as ICollection).SyncRoot)
{
    _collection.Add(newObject);
}

SyncRoot provides a universal way of accessing the synchronization object of the collection. So if you subclass a collection and create your own type, you will still be able to access and use this object and work in concert with whatever synchronization the class provides.

Implementing Concurrency in a derived type

If you wish to implement a thread safe collection as a derived type, it is still beneficial to use the SyncRoot property. It gives you access to the same lock object inside and outside your class, and allows extra flexibility in handling non-trivial situations.

C#
lock((this as ICollection).SyncRoot)
{
    T removedItem = this[oldIndex];
    base.RemoveItem(oldIndex);
    base.InsertItem(newIndex, removedItem);
}

Because lock() internally uses Monitor, it is safe to call lock on the same thread recursively. This allows us to combine several operations under the same external lock:

C#
lock ((_collection as ICollection).SyncRoot)
{
    T removedItem = _collection[Index];
    _collection.RemoveAt(oldIndex);
    _collection.Insert(newIndex, removedItem);
}

When lock is applied to SyncRoot inside RemoveAt, Insert, etc., it will not block. It will increase the reference counter and continue with the operation. Once the operation is done, it will decrease the counter and release the lock once all of them are done.

History

  • 10/27/2011 - Released.
  • 04/11/2012 - Recategorized as Tip

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
Senior Software Engineer with over 20+ years of experience in variety of technologies, development tools and programming languages.

Microsoft Certified Specialist programming in C#, JavaScript, HTML, CSS

Comments and Discussions

 
GeneralNice trick, but hardly usable with WPF Pin
Anton-V-K5-Apr-23 5:26
Anton-V-K5-Apr-23 5:26 
QuestionConcurrent Collections Pin
YandyZM31-Oct-11 11:21
YandyZM31-Oct-11 11:21 
AnswerRe: Concurrent Collections Pin
Eugene Sadovoi31-Oct-11 13:44
Eugene Sadovoi31-Oct-11 13:44 
GeneralRe: Concurrent Collections Pin
YandyZM1-Nov-11 4:43
YandyZM1-Nov-11 4:43 
AnswerRe: Concurrent Collections Pin
Eugene Sadovoi8-Nov-11 3:43
Eugene Sadovoi8-Nov-11 3:43 
AnswerRe: Concurrent Collections Pin
Wojciech Barański5-Apr-19 20:31
Wojciech Barański5-Apr-19 20:31 
GeneralMy vote of 4 Pin
SledgeHammer0128-Oct-11 7:49
SledgeHammer0128-Oct-11 7:49 
AnswerRe: My vote of 4 Pin
Eugene Sadovoi28-Oct-11 7:52
Eugene Sadovoi28-Oct-11 7:52 
Questionuseful Pin
BillW3328-Oct-11 6:25
professionalBillW3328-Oct-11 6:25 
AnswerRe: useful Pin
Eugene Sadovoi28-Oct-11 7:24
Eugene Sadovoi28-Oct-11 7:24 
GeneralEvents Pin
stooboo27-Oct-11 23:34
stooboo27-Oct-11 23:34 
GeneralRe: Events Pin
Eugene Sadovoi28-Oct-11 4:05
Eugene Sadovoi28-Oct-11 4:05 
GeneralRe: Events Pin
stooboo28-Oct-11 7:39
stooboo28-Oct-11 7:39 
GeneralRe: Events Pin
Eugene Sadovoi28-Oct-11 7:49
Eugene Sadovoi28-Oct-11 7:49 
QuestionSynchronization needs to be handled with care Pin
John Brett27-Oct-11 22:43
John Brett27-Oct-11 22:43 
AnswerRe: Synchronization needs to be handled with care Pin
Julien Villers27-Oct-11 23:09
professionalJulien Villers27-Oct-11 23:09 
AnswerRe: Synchronization needs to be handled with care Pin
Eugene Sadovoi28-Oct-11 4:29
Eugene Sadovoi28-Oct-11 4:29 
QuestionThought Pin
cdkisa27-Oct-11 14:42
cdkisa27-Oct-11 14:42 
AnswerRe: Thought Pin
Eugene Sadovoi28-Oct-11 7:36
Eugene Sadovoi28-Oct-11 7:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.