Using instances of Object for lock C# with Example



Using instances of Object for lock C# with Example

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

When you use the yield keyword in a statement, you indicate that the method, operator, or get accessor in which it 
appears is an iterator. Using yield to define an iterator removes the need for an explicit extra class (the class that 
holds the state for an enumeration) when you implement the IEnumerable and IEnumerator pattern for a custom 
collection type. 

0 Comment's

Comment Form

Submit Comment