2

Can ICollection<T>.Count property getter be considered atomic (and, therefore, threadsafe)?

Thank you.

3 Answers 3

7

It completely depends on the collection; ICollection<T> is just an interface.

Every collection that I know of simply returns an Int32 field in its Count getter, so it usually is atomic.
However, there is never a guarantee that the count didn't change just after you fetched the property.

Sign up to request clarification or add additional context in comments.

Comments

7

No, as you can only make that assumption for implementations, not an interface.

Comments

3
  • Atomic would only make sense for implementation and not interface. You could have two implementations: one non-thread-safe implementation one thread safe.

  • List<T> is not thread safe since it does not use InterLocked.

1 Comment

How would using Interlocked make the List<T> implementation of Count thread-safe? The Count property just returns an int field, which is an atomic read. Of course, there's always the possibility that the count is already stale by the time it's returned to the caller, but that's just as likely if Interlocked was used.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.