using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using GcDevicePc.Common;

namespace GcDevicePc.ProThread
{
    class ChannelDataTh
    {
        /// <summary>
        /// 单实例对象
        /// </summary>
        private static ChannelDataTh instance = null;  //静态私有成员变量
        /// <summary>
        /// 单实例对象锁
        /// </summary>
        private static object _lock = new object();

        /// <summary>
        /// 数据锁
        /// </summary>
        private static object _datalock = new object();

        #region 单实例实现
        public static ChannelDataTh GetInstance()
        {
            if (instance == null)
            {
                lock (_lock)
                {
                    if (instance == null)
                    {
                        instance = new ChannelDataTh();
                    }
                }
            }
            return instance;
        }
        #endregion

        #region 分析仪数据读取线程
        private Thread _tGetChannelData;     //分析仪读取线程
        private ManualResetEvent channeldata_mre = new ManualResetEvent(false);  //信号控制量
        #endregion

        public void ChannelDataThStart()
        {
            if (channeldata_mre != null)
            {
                channeldata_mre.Reset();
            }

            if (_tGetChannelData != null)
            {
                _tGetChannelData.Abort();
            }

            _tGetChannelData = new Thread(ChannelDataThProc);
            _tGetChannelData.Priority = ThreadPriority.Highest;
            //  _tGetAnalyzerData.IsBackground = true;
            _tGetChannelData.Start();
        }

        /// <summary>
        /// 判断线程工作状态
        /// </summary>
        /// <returns></returns>
        public bool ThreadWorking()
        {
            if (_tGetChannelData != null)
            {
                if (_tGetChannelData.ThreadState == ThreadState.Running || (_tGetChannelData.ThreadState & ThreadState.WaitSleepJoin) != 0)
                    return true;
                else
                    return false;
            }
            return false;
        }

        /// <summary>
        /// 线程停止
        /// </summary>
        public void ChannelDataThStop()
        {
            channeldata_mre.Set();
        }

        /// <summary>
        /// 线程工作函数
        /// </summary>
        private void ChannelDataThProc()
        {
            while (!channeldata_mre.WaitOne(500))
            {
                ReadChannelData();
            }
        }

        private void ReadChannelData()
        {
            MoudbusOperation.GetInstance().Get_Channel_Data();
        }
    }
}
