单例模式-多线程单例模式

using System;
using System.Threading;


namespace Rattan.ERP.TMS.Services.EOP
{
  /// <summary>
  /// 单线程队列,创建 EOP 订单
  /// </summary>
  public class ThreadCreateEopOrder
  {
    #region 单例模式
    private ThreadCreateEopOrder()
    {
    }
    /// <summary>
    /// 线程安全锁
    /// </summary>
    private static readonly object m_lock = new object();
    private volatile static ThreadCreateEopOrder m_instance = null;
    /// <summary>
    /// 实例化 ThreadCreateEopOrder 对象
    /// </summary>
    /// <returns></returns>
    public static ThreadCreateEopOrder CreateInstance()
    {
      if (m_instance == null)
      {
        lock (m_lock)
        {
          if (m_instance == null)
            m_instance = new ThreadCreateEopOrder();
        }
      }
      return m_instance;
    }
    #endregion


    #region 枚举
    /// <summary>
    /// 枚举
    /// </summary>
    public enum EnumState
    {
      /// <summary>
      /// 未开始
      /// </summary>
      None = 0,   
      /// <summary>
      /// 开始
      /// </summary>
      Start = 1,   
      /// <summary>
      /// 正在执行
      /// </summary>
      Doing = 2,   
      /// <summary>
      /// 执行完毕
      /// </summary>
      End = 3,    
    }


    private volatile static EnumState m_state = EnumState.None;
    /// <summary>
    /// 执行状态
    /// </summary>    
    public static EnumState State
    {
      get { return m_state; }
      //set { m_State = value; }
    }
    #endregion


    /// <summary>
    /// 线程
    /// </summary>
    private Thread m_thread = null;


    /// <summary>
    /// 开启一个进程
    /// </summary>
    public void RunWork()
    {
      //确保临界区被一个Thread所占用 
      lock (m_lock)
      {
        if (State == EnumState.None || State == EnumState.End)
        {
          //初始化线程
          m_thread = new Thread(new ThreadStart(DoWork))
          {
            Name = "创建 EOP 订单线程"
          };
          m_thread.Start();
          //WorkFromDate = DateTime.Now;
          m_state = EnumState.Start;
        }
      }
    }


    /// <summary>
    /// 处理消息队列中的数据
    /// </summary>
    private void DoWork()
    {
      try
      {
        m_state = EnumState.Doing;
#region 需要执行的主要程序代码
        CreateEopOrder eopOrder = new CreateEopOrder();
        eopOrder.Start();
#endregion
      }
      catch (Exception ex)
      {
        Grass.Log.ExceptionsStack.RegisterError(ex);
      }
      finally
      {
        m_state = EnumState.End;
      }
    }


  }
}

单例模式-多线程单例模式,布布扣,bubuko.com

单例模式-多线程单例模式

上一篇:重新整理 .net core 实践篇—————配置系统之间谍[八](文件监控)


下一篇:com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.baomidou.mybatisplus.core.metadata.IPage