Does blocking (objlocker) make this object a thread-safe application wide? Are static members automatically thread safe?

When you lock an object, is that object locked throughout the application?

For example, this snippet from C # 3.0 under "Short Article" 19.6.1 "Thread Safety Types and the .NET Framework":

static void AddItems(  )
  {
    for (int i = 0; i < 100; i++)
      lock (list)
        list.Add ("Item " + list.Count);

    string[] items;
    lock (list) items = list.ToArray(  );
    foreach (string s in items) Console.WriteLine (s);
  }

      

Is there a first lock:

lock (list)
        list.Add ("Item " + list.Count);

      

prevent another thread from accessing:

lock (list) items = list.ToArray(  );

      

or can both be done at the same time?

And does the CLR make automatic threading of static methods safe? Or is it up to the developer?

Thanks, John

+1


source to share


3 answers


class UsefulStuff {
    object _TheLock = new object { };
    public void UsefulThingNumberOne() {
        lock(_TheLock) {
            //CodeBlockA
        }
    }
    public void UsefulThingNumberTwo() {
        lock(_TheLock) {
            //CodeBlockB
        }
    }
}

      

CodeBlockA

and CodeBlockB

cannot run concurrently on different threads because they are both locked on the same object instance _TheLock

.



The methods itself _TheLock

are not completely affected.

+3


source


Another thing to note is that ARE's static constructors are executed in a thread-safe manner at runtime. If you create a singleton and declare it as:

public class Foo
{
    private static Foo instance = new Foo();

    public static Foo Instance
    {
        get { return instance; }
    }
}

      



Then it will be thread safe. If, however, you create a new Foo inside the instance then you will need to write your own thread safety (i.e. lock the object)

+5


source


The CLR does not make automatic static methods thread-safe; you have to do it yourself.

lock (list) uses this object as a lock, so if another thread reaches another point with a lock (list) (with the same list object), the other thread will block until the first thread releases the lock.

To be clear, lock (foo) does not "lock foo", but acquires the lock associated with foo so that the critical section (the statement in "lock (o) stmt") is only executed when the current thread has acquired the lock.

+3


source







All Articles