Bastien
Bastien

Reputation: 1013

Lock writing a Property

In my class I have this property :

public List<MyObject> mCollection { get; set; }

This collection is used in some different threads.

What I would like to do it's to allow writing this property only when all threads have finished reading mCollection.

Something like taking and release a token, and to allow writing only when all token are released. Is there something like that in the framework ?

Thanks in advance

Upvotes: 4

Views: 110

Answers (2)

Savvas Kleanthous
Savvas Kleanthous

Reputation: 2745

While there are some constructs that can help like SemaphoreSlim, I strongly believe that there are far better approaches to your problem. This could be like using ImmutableList instead of List and changing your calling code to use that.

The use of a locking mechanism in your scenario, has to be implemented by the callers and the ones who have access to your property. Since this is public, you do not have any means to enforce callers to submit to a locking mechanism, other than retrieving the list, wrapped in an IDisposable that will release the lock on dispose (it is a bit more complex that this as you have to lock before getting an IEnumerator). Again however, I believe that a restructuring of your source code to use proven constructs is a better solution.

If you need to chain events or processors, I would strongly suggest that you use TPL Dataflow. This will free you from the problems faced when one thread waits for something to become available, and will also result in significantly better designed and more easily maintainable code.

Upvotes: 0

usr
usr

Reputation: 171188

There are many ways you can achieve that. To keep it simple, make your readers cooperate by synchronizing with each other.

  • Let readers take a read lock with ReaderWriterLockSlim. Have the writer take a write lock.
  • Make readers signal a CountdownEvent. Make the writer wait on it.
  • Make all readers and writers SignalAndWait a Barrier so that the writer proceeds only when everyone is done.

Pick what matches your scenario.

Upvotes: 1

Related Questions