c# - Is lock() type-cast safe? -


  public class A {} public class B: A {} void foo () {A a = new B ( ); B B = A to B as; }  

For a given installation setup, lock (a) lock (b) is equivalent to < P> I mean, will no longer mutually exclusive? If I lock (a) is a thread and Lock (B) A and thread, so I'm the code for an example of mutually exclusive sign will receive a B has already been created?

Yes lock (a) {} is equal to Lock ( b) {} .

indicates that the lock statement to reference the type of a given object by a significant segment of the mutual exclusion lock in a statement to mark the block.

A and b are both the same thing, yes, they are equal. In fact, A and b is a reference to the object of both.

Cast operation between the reference types of built-in run-time type of the object does not change; The only way to change that object is used in the context of the object as being. .

A quick test program shows that it is in fact the way this document is treated:

  namespace Console Application 2 {public class A {} public class B: a {} class program {static a a = new B (); Stable zero MyThread () {B B = A as B; Lock (B) {Console. WrightLine ( "B lock acquisition"); Kansolaprakasalaina ( "B lock issue"); }} Static void main (String [] Arges) {System.Threading.Thread t = new system. Threading. Thread (MyThread); Lock (A) {Console. Vidalaina ( "lock acquisition"); t.Start (); System.Threading.Thread.Sleep (10000); Kansolaprakasa line ( "A lock release"); }}}}  

A lock was acquired ... ... 10 seconds have / to release a lock - P>


Comments