Decrypt Lazy & lt; T & gt; and decrypt lazy

Source: Internet
Author: User

Decrypt Lazy <T> and decrypt lazy
1. Use of Lazy <T>

I accidentally saw a piece of code and used Lazy when creating an object. As the name suggests, Lazy must be delayed loading. So how does it create an object and when does it create an object? First, let's look at the code of this column:

    public class OrderController : Controller    {        private readonly Lazy<OrderService> _orderSrv = new Lazy<OrderService>();                public ActionResult CreateOrder(OrderModel model)        {            var result = _orderSrv.Value.CreateOrder(model);            return Json(result);        }    }

It is very easy to use. Put OrderService in Lazy <T>, and then create the OrderService object only when _ orderSrv. Value is used.

So the question is, every time _ orderSrv. Value is clicked, an object is created? Think of this, the basic conditioned reflection of the program ape, and press F12 on Lazy.

 

In the constructor, there is an isThreadSafe parameter. The default value is true. OK. Refer to the msdn example for testing.

        static void Main(string[] args)        {                        Lazy<int> number = new Lazy<int>(() => Thread.CurrentThread.ManagedThreadId);            Thread t1 = new Thread(() =>                 Console.WriteLine("number on t1 = {0} ThreadID = {1}"
,number.Value, Thread.CurrentThread.ManagedThreadId)); t1.Start(); Thread t2 = new Thread(() => Console.WriteLine("number on t2 = {0} ThreadID = {1}"
,number.Value, Thread.CurrentThread.ManagedThreadId)); t2.Start(); Thread t3 = new Thread(() => Console.WriteLine("number on t3 = {0} ThreadID = {1}"
, number.Value,Thread.CurrentThread.ManagedThreadId)); t3.Start(); Console.ReadLine(); }

Result:

 

Obviously, after the number is initialized by the thread ID = 10, the value remains unchanged, indicating that the three threads use the same instance.

Try isThreadSafe = false again.

Lazy <int> number = new Lazy <int> () => Thread. CurrentThread. ManagedThreadId,False);

Result (1 ):

 

After the number instance is used by the thread ID = 11, other threads cannot use it correctly. number. value = 0 indicates that int is not.

Result (2 ):

The error is reported directly. In my understanding, Lazy does not support multi-thread concurrency at this time.

2. valueFactory of Lazy <T>

Continue to find the explanation in f12:

 

Based on the above example, valueFactory is a delegate, and valueFactory is used to create this instance when number. value is used.

We can see that Lazy <T> is still very powerful,You can use the default T constructor to create an instance or the specified Func to create an instance. It also supports multi-thread security. 

3. Working Principle of Lazy <T>

Use the decompilation plug-in to check the Code:

      static Lazy()        {            Lazy<T>.ALREADY_INVOKED_SENTINEL = () => default(T);            Lazy<T>.PUBLICATION_ONLY_SENTINEL = new object();        }
        [__DynamicallyInvokable]        public Lazy(Func<T> valueFactory, LazyThreadSafetyMode mode)        {            if (valueFactory == null)            {                throw new ArgumentNullException("valueFactory");            }            this.m_threadSafeObj = Lazy<T>.GetObjectFromMode(mode);            this.m_valueFactory = valueFactory;        }

We can see that default (T) and this. m_valueFactory = valueFactory probably know how to create an instance.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.