I have a class with a public property exposing a collection of objects. The collection is being maintained within the class by multiple threads. The objects within the collection will change and also the properties of those objects.

Observers can view the collection as read only from other threads, for example a gridview uses the collection as the itemsource.

Will the code be thread safe if:

1) I lock the critical section within the class during any changes to the collection or objects within the collection
2) I mark the collection as volatile

Thanks

I think this discussion can put some light on your problem: When should the volatile keyword be used in C#?

Hi Antenka

Thanks for your reply. It looks like using the volatile keywork will not be suitable for what I am trying to do.

My problem therefore is that I can only control the locks within the class, not for any references to the collection from outside the class.

Even if I only allow access to the collection objects using a property get, the object which will be passed back will still be a reference to an object in the collection. As far as I can understand, this will again be thread unsafe.

What I need to do it allow the collection to be maintained in a thread safe way from within the class whilst allowing observers read only access to the collection in a thread safe from outside the class.

I would really appreciate any help or advice you could give me.

Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.