Thread safety - Collection property

  • Thread starter Thread starter GeezerButler
  • Start date Start date
G

GeezerButler

If i have a property like this in my class:

private IList<SomeClass> products;
public IList<SomeClass> Products
{
get {return products;}
set {products = value;}
}

Is there any way to make this property thread safe?
If i try to lock getter and setter, different threads can still mutate
the list by calling myClass.Products.Add(), right?
 
If i have a property like this in my class:

private IList<SomeClass> products;
public IList<SomeClass> Products
{
get {return products;}
set {products = value;}

}

Is there any way to make this property thread safe?
If i try to lock getter and setter, different threads can still mutate
the list by calling myClass.Products.Add(), right?

There's really no good concept of a thread-safe collection - unless
it's immutable, of course.
You can synchronize access to each individual operation, but that's
only partially safe. For instance, if you iterate over a collection
using "foreach" in one thread, and change the contents in another
thread, you should get an exception in the iterating thread - even if
each individual operation is synchronized. You could add a "ForEach"
method taking a delegate which locks the collection while it's
iterating, but that would be quite extreme.

Jon
 
You can synchronize access to each individual operation, but that's
only partially safe.

By that, do you mean that i can synchronise the access to the 'Add'
method of products? But how is that possible?
 
GeezerButler said:
By that, do you mean that i can synchronise the access to the 'Add'
method of products? But how is that possible?

You'd need to use an appropriate collection, such as
SynchronizedCollection<T>.
 
If i have a property like this in my class:

private IList<SomeClass> products;
public IList<SomeClass> Products
{
get {return products;}
set {products = value;}
}

Is there any way to make this property thread safe?
If i try to lock getter and setter, different threads can still mutate
the list by calling myClass.Products.Add(), right?

In addition to what Jon wrote, one alternative is to provide collection
accessor features in the containing class itself. This is only
appropriate if that class is basically a wrapper for the collection and
little else, but it would certainly be a way to synchronize access to the
collection without the collection itself needing to be thread-safe. In
that way, only the class holding the collection ever actually sees the
collection itself, and can control access to it as needed.

Pete
 
Back
Top