When reading the MSDN documentation it always lets you know if a class is thread safe or not. My question is how do you design a class to be thread safe? I am not talking about
In addition to the other excellent answers here, consider another angle as well.
It isn't enough that the internal data structure of the class is 100% thread safe if the public API has multi-step operations that cannot be used in a thread-safe manner.
Consider a list class that has been built such that no matter how many threads are doing no matter how many types of operations on it, the internal data structure of the list will always be consistent and OK.
Consider this code:
if (list.Count > 0)
{
var item = list[0];
}
The problem here is that between the reading of the Count property and the reading of the first element through the [0] indexer, another thread might have cleared out the contents of the list.
This type of thread safety is usually forgotten when the public API is created. Here, the only solution is for the calling code to manually lock on something on each such type of access to prevent the code from crashing.
One way to solve this would be for the list type author to consider typical usage scenarios and add the appropriate methods to the type:
public bool TryGetFirstElement(out T element)
then you would have:
T element;
if (list.TryGetFirstElement(out element))
{
....
presumably, TryGetFirstElement works in a thread-safe manner, and would never return true at the same time as it is not able to read the first element value.