Tuesday, October 29, 2013

C#.net - Lazy Loading in C#.net

In this article i will show you how to use Lazy loading in C#.net.

What is Lazy Loading???
Lazy loading is a concept or design pattern commonly used in computer programming to defer initialization of an object until the point at which it is needed. It can contribute to efficiency in the program's operation if properly and appropriately used. The opposite of lazy loading is eager loading.
In short i can say that,Load object on Demand.

Let take a simple program. 
Suppose we have Customer and Order entity class.Assume that a single customer can have more than orders.If we want show orders for single customer then we need to load orders associate with Customer.Loading of orders can make performance hit badly if data is huge when customer object is initialized first time.

For avoiding the situation we can use Lazy Loading.Load the order object on demand whenever the Order object used in program.This is will make faster loading customer object and give the better performance of application.

This is a new feature of C# 4.0 its can be used when we are working with large objects when its not in use. This article will explain you about Lazy<T> class.

Theory part done now let see practical oriented program.

Step 1
Create a Console application give the solution name as SolLazyLoading.

Step 2
First a Create Order Entity class,it is look like this 
  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SolLazyLoading
{
    public class Order
    {
        public int OrderNo
        {
            get;
            set;
        }
    }
}

Step 3
Create a Customer class,it is look like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SolLazyLoading
{
    public class Customer
    {
        #region Field 
        // 1.Step. Initialized Lazy Loading Orders
        private Lazy<List<Order>> _GetOrders;

        #endregion

        #region Constructor

        public Customer()
        {
            this.CustomerName = "Yogesh Naik";

            // 3 Step. Create a Instance of Lazy List Order and Pass GetOrderData function as Parameter to get Order List.
            _GetOrders = new Lazy<List<Order>>(() => GetOrderData());

            // or you write like this // it's not a best practice
            //_GetOrders = new Lazy<List<Order>>(() => {
            //    List<Order> OrderList = new List<Order>();
            //    OrderList.Add(new Order() { OrderNo = 1 });
            //    OrderList.Add(new Order() { OrderNo = 4 });
            //    OrderList.Add(new Order() { OrderNo = 10 });
            //    return OrderList;
            //});
        }

        #endregion

        #region Property

        public String CustomerName
        {
            get;
            set;
        }

        public List<Order> GetOrders
        {
            get
            {
                // 2 Step. Get a Lazy Initialized value
                return _GetOrders.Value; 
            }
           
        }

        #endregion

        #region Private Method
        /// <summary>
        /// Get Order Data 
        /// </summary>
        /// <returns>List</returns>
        private List<Order> GetOrderData()
        {
            try
            {
                // Set Orders Data
                List<Order> OrderList = new List<Order>();
                OrderList.Add(new Order() { OrderNo = 1 });
                OrderList.Add(new Order() { OrderNo = 4 });
                OrderList.Add(new Order() { OrderNo = 10 });

                return OrderList;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message); 
            }
        }

        #endregion
    }
}

In the constructor of customer class, properties are initializing and declaring Lazy List object, which is generic List of orders and filled by GetOrderData method. This method will only call when lazy list object will be use.

Step 4
The following main method show behavior of Lazy Loading,it is look like this 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SolLazyLoading
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Instance of Customer Object.
            Customer CustObj = new Customer();

            // Customer Name should be load but not a load Order Object here when Customer constructor called.
            System.Console.WriteLine("Customer Name : {0}",CustObj.CustomerName);

            foreach (Order OrderObj in CustObj.GetOrders) // here load a Order Object whenever it is used. i.e That is Lazy Loading.
            {
                System.Console.WriteLine("Order No : {0}", OrderObj.OrderNo);
            }
        }
    }
}

Now lets a put a Debug point where created instance of customer class, it is like like this



Click on Image for better view

Press F5 to run program on debug mode,Press F10 and now look at local window that still getorders object not load.Now Press F10 again,look at local window now.



Click on Image for better view

Here GetOrder object load whenever it is used.

So i hope you understand the concept of Lazy Loading(Load Object on Demand).

Run the Project.

Download
Download Source Code

4 comments:

  1. Great article...........

    ReplyDelete
    Replies
    1. Thank You for sharing your article, This is an interesting & informative blog. It is very useful for the developer like me. Kindly keep blogging. Besides that Wisen has established as Best Corporate Training in Chennai .

      Nowadays JavaScript has tons of job opportunities on various vertical industry. Know more about JavaScript Framework Training visit Corporate Training Companies in India.

      This post gives me detailed information about the technology. corporate training companies in india

      Delete
  2. you are rockstar dude.really great article..keep it up dude..........

    ReplyDelete
  3. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Training in Chennai. or learn thru Dot Net Training in Chennai. Nowadays Dot Net has tons of job opportunities on various vertical industry.
    or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry.

    ReplyDelete