Essential C# Lock Statement  Suggest an edit

Using instances of Object for lock

When 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).

Table Of Contents
22 Enum
107 Stream
108 Timers
117 Lock Statement
  ↑ ↓ to navigate     ↵ to select     Esc to close