Wednesday, January 11, 2012

Lazy Types (.Net 4)


Let’s look at definition of Lazy types as defined
[SerializableAttribute]
[ComVisibleAttribute(false)]
[HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true,
        ExternalThreading = true)]
public class Lazy<T>

A variable which is declared to be of Lazy type is initialized when its accessed first time.
Lazy type exposes following 2 properties
1)  IsValueCreated : It’s a Boolean property and indicates whether a value has been created for concerned type.
2)  Value : It returns actual instance for concerned type.


Lazy type has following constructors:

1)<T>() : It’s a default constructor and here it used default constructor defined for type “T”.
2)Lazy<T>(bool isThreadSafe): Here framework uses default constructor for initialization. isThreadSafe indicates whether this instance is usable by multiple threads. If isThradSafe is set as True then then  ThreadSafetyMode for the instance variable  is set as “LazyThreadSafetyMode.ExecutionAndPublication” else it sets ThreadSafetyMode as “LazyThreadSafetyMode.None”.
3) Lazy<T>(Func<T>) : Here framework uses Func method to initialize concerned variable.
4) Lazy<T>(LazyThreadSafeMode mode) : It uses Default constructor for type to initialize concerned instance. LazyThreadSafeMode enum has 3 values (None, PublicationOnly, ExecutionAndPublication).
“LazyThreadSafeMode.None” indicates instance is not thread safe.
“LazyThreadSafeMode.PublicationOnly” indicates when multiple threads try to initialize , all of them are allowed but whichever thread completes first, sets the value for instance.
“LazyThreadSafeMode.ExecutionAndPublication” indicates that only one thread is allowed to initialize instance.
Refer to here, to get more information about exception and their behavior wrt to LazyThreadSafeMode.
5) Lazy<t>(Func<t> valueFactory, bool isThreadSafe): It uses specified function for initialization and specifies ThreadSafe while creation.
6) Lazy<T>(Func<T>,LazyThreadSafeMode mode) : It uses specified function for inilitalization and specifies ThereadSafeMode for instance.


Now I am going to show how we can implement Singleton using Lazy types.
I have defined “LazySingleton” class which has a public static property Instance which returns a Lazy type variable.


using System;
 
namespace LazyTypes
{
 
   //Setting class as sealed to avoid any inheritance for this class.
   public sealed class LazySingleton
   {
        //Lazy type variable 
        private static readonly Lazy<LazySingleton> _instance = new Lazy<LazySingleton>(() => new LazySingleton());
 
        // Setting constructor as private to prevent direct instantiation.
        private LazySingleton()
        {
 
        }
 
        // public property to expose instance
        public static LazySingleton Instance
        {
            get
            {
                    return _instance.Value;
            }
        }
    }
}

No comments:

Post a Comment