Using instances of Object for lock
suggest changeWhen using C#’s inbuilt lock
statement an instance of some type is needed, but its state does not matter. An instance of object
is perfect for this:
public class ThreadSafe {
private static readonly object locker = new object();
public void SomeThreadSafeMethod() {
lock (locker) {
// Only one thread can be here at a time.
}
}
}
NB. instances of Type
should not be used for this (in the code above typeof(ThreadSafe)
) because instances of Type
are shared across AppDomains and thus the extent of the lock can expectedly include code it shouldn’t (eg. if ThreadSafe
is loaded into two AppDomains in the same process then locking on its Type
instance would mutually lock).
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents