I was recently in an interview and the tech guy asked me about how to make an application thread-safe.
Well, after explaining the lock()
correctly, he said it is not a good idea to have the object as static.
private static readonly object _syncLock = new object();
He claimed the reason is that static makes that object slower for threads to lock than if it was non static. Is this true?
EDIT: Nonetheless I am still not sure. What is the difference between these three approaches?
private static readonly object _syncLock = new object();
public static readonly object _syncLock = new object();
private readonly object _syncLock = new object();
If a lock object should be static or not depends on the object you want to lock. If you want to lock an instance of a class you cannot use a static lock object. If you want to lock static data you cannot use an instance lock object. So there seems not to be any choice.
You could think about using a static or an instance lock object to lock the access to instance data, but this results in different behaviors. With an instance lock object you lock only an instance while an static lock object will lock all instances. So no choice for performance tuning here, too.
He claimed the reason is that static is run at runtime instead of compilation and would make that object slower for threads to lock than if it was non static.
This doesn't really make any sense - I think either the interviewer did not know what he was talking about, or maybe you misunderstood his point.
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