Thread safety - Collection property

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?
 
J

Jon Skeet [C# MVP]

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
 
G

GeezerButler

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?
 
J

Jon Skeet [C# MVP]

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>.
 
P

Peter Duniho

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top