Lazy懒加载

在.NET4.0中,可以使用Lazy<T> 来实现对象的延迟初始化,从而优化系统的性能。延迟初始化就是将对象的初始化延迟到第一次使用该对象时。

 

Lazy<T> 对象初始化默认是线程安全的,在多线程环境下,第一个访问 Lazy<T> 对象的 Value 属性的线程将初始化 Lazy<T> 对象,以后访问的线程都将使用第一次初始化的数据。

 

1、 System..::.Lazy<(Of <(T>)>) 类。 Lazy<(Of <(T>)>) 支持线程安全(在一个线程中创建实例后,对其它线也是共享的),并提供一致的异常传播策略。

2、在 Lazy<(Of <(T>)>) 构造函数中传递一个委托,用于在创建时调用包装类的特定构造函数重载,并执行所需的任何其他初始化步骤

学习:http://www.cnblogs.com/lori/archive/2012/06/12/2546133.html

-------错误:延迟初始化的类型没有公共的无参数构造函数

using System;


namespace KLB.Ins.Insured.Common.Utils
{
    public class InterfaceLogQueue:KLB.Common.Queue.MsmqQueue<InterfaceLog>
    {

        private static readonly Lazy<InterfaceLogQueue> _instance = new Lazy<InterfaceLogQueue>(() =>
        {
            return new InterfaceLogQueue();
        }, true);
        private InterfaceLogQueue():base(InsuredConstants.InterfaceLogQueue_WorkThreadCount,InsuredConstants.InterfaceLogQueue_FullPath)
        {

        }
        public static InterfaceLogQueue Instance
        {
            get { return _instance.Value; }
        }

        public void SendMessage(InterfaceLog log)
        {
            try
            {
                System.Messaging.Message message = new System.Messaging.Message(log, this.Formatter);
                message.Label = log.ChannelId.ToString()+log.PartnerId.ToString()+log.CustomerId.ToString()+log.InterfaceId.ToString();
                message.Priority = System.Messaging.MessagePriority.Normal;
                this.Send(message);
            }
            catch (Exception ex)
            {
                KLB.Common.Logging.Logger.Write("消息发送失败,原因:" + ex.ToString());
            }
        }
    }
}

 

posted @ 2017-03-02 09:53  wjl910  阅读(129)  评论(0)    收藏  举报