List.Add is an instance member. That means it's not guaranteed to be thread-safe. What does this mean?
Possibility 1. That if two threads invoke .Add on different instances, there could be an unexpected result depending on the phase of the moon?
Possibility 2. That if two threads invoke .Add on the same instance, there could be an unexpected result depending on the phase of the moon and if the instances are different there is no potential problem.
Possibility 3. Microsoft doesn't want people to use threading at all so they wrote .NET to be ambiguous.
Possibility 1 is not the case. It would be so unusual for an instance method to cause problems for other instances that this would be documented clearly (not just with a statement pointing this out, but also with some justification as this would generally be a sign of very bad coding, so if there was a good reason for it, it would be pointed out).
Possibility 3 is not the case, as they've just documented the threading behaviour.
Possibility 2 is partly the case. However, the interaction can also be with one thread calling Add and another calling a different non-threadsafe instance method.
The majority of mutable classes supplied by the framework are threadsafe for static members and non-threadsafe for instance methods. This is with good reason.
If a static method is not thread-safe, it is very difficult to make calls to that method in a thread-safe manner, especially if the class may be used by different layers of code written by different people. This makes the effort of making such methods threadsafe almost always justified. Most such members are also relatively easy to make threadsafe anyway (if one avoids having mutable static state, which is always a good thing to avoid).
Much use of individual objects will be by one thread at a time, with no prospect of it being accessed by another thread. This makes the difficulty of ensuring correctness, with the risk of deadlock if it goes wrong, and the overhead imposed on performance, hard to justify. It is also relatively easy for the person using the class to ensure that an instance that is used by multiple threads, is used in a threadsafe manner.
There's a heavy emphasis on the "relatively" there, as writing threadsafe code is not always easy. Sometimes its pretty easy (immutable classes take a bit of work to make non-threadsafe!), but more often it's very hard (hence many questions on the topic here and elsewhere).
Yet this is precisely why the burden should be put on the user in such cases. To make such a class entirely threadsafe is so difficult (indeed, sometimes provably impossible) that the results would be unacceptable to most users, who are the people in the best position to judge just what protection is needed in a given case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With