I have this question.
public class Foo : object
{
public override bool Equals(obj a, objb)
{
return ((Foo)a).Bar.GetHashCode() == ((Foo)b).Bar.GetHashCode();
}
}
Suppose I want to make Foo threadsafe. Do I need to synchronize calls to GetHashCode()?
Even if you were going to add synchronization, what would you synchronize against?
I would say as a general rule
GetHashCodeshould always be threadsafe, but the docs don’t state a requirement for thread safety. A consumer ofBarcan’t really guarantee it’s usage is threadsafe unlessBarprovides thread safety internally.Let’s say
Baruses two internal fields to calculate the hash code. If another thread is in the process of updating the fields and only one has changed, you’ll be able to get aGetHashCode()result after one field was updated but before the second was updated, unlessBarinternally provides synchronization.