/// <summary>
 /// 停止本服务,清理
 /// </summary>
 protected override void OnStop()
 {
     //停止全部线程
     LogInToEvent.WriteDebug("开始停止进程");
     LogInToEvent.WriteDebug("停止线程池");
     foreach (var t in pool)
     {
         t.Abort();
     }
     LogInToEvent.WriteDebug("准备结束应用程序");
     System.Diagnostics.Process.GetCurrentProcess().Kill();
 }
        /// <summary>
        /// 启动本服务,调度初始化
        /// </summary>
        /// <param name="args"></param>
        protected override void OnStart(string[] args)
        {
            AutoLog = true;
            try
            {
                LogInToEvent.WriteInfo("尝试启动");
                InitAndStart();
            }
            catch (Exception e)
            {
                LogInToEvent.WriteError(e.ToString());

                System.Diagnostics.Process.GetCurrentProcess().Kill();
            }
        }
        /// <summary>
        /// 在web访问到来时取得访问报告,并返回给用户
        /// </summary>
        /// <param name="a"></param>
        void Web_AfterConnectionGetReportAndSendToUser(object a)
        {
            System.Net.Sockets.TcpClient socketcomein = a as System.Net.Sockets.TcpClient;

            if (socketcomein == null)
            {
                LogInToEvent.WriteError("未知错误:socketcomein == null");
                return;
            }
            try
            {
                var stream = socketcomein.GetStream();
                System.IO.StreamReader rstream = new System.IO.StreamReader(stream);
                string i = rstream.ReadLine();
                var where = i.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                if (!
                    (where.Length == 3 &&
                     where[1].Trim().StartsWith("/"))
                    )
                {
                    string errorMessage = "请求格式错误,请发送 GET / HTTP1.1 \n" + i;
                    foreach (var p in where)
                    {
                        errorMessage += "\n" + p + "\n";
                    }
                    var error_gs = System.Text.Encoding.UTF8.GetBytes(errorMessage);
                    stream.Write(error_gs, 0, error_gs.Length);
                    stream.Close();
                    socketcomein.Close();
                    return;
                }
                string report = Web_GetReport(where[1]);
                string head   = "http/1.1 200 ok\n" +
                                "Content-Type: text/html\n";
                byte[] content = System.Text.Encoding.UTF8.GetBytes(report);
                head += "Content-Length:" + content.Length + "\n\n";
                var headstr = System.Text.Encoding.UTF8.GetBytes(head);
                stream.Write(headstr, 0, headstr.Length);
                stream.Write(content, 0, content.Length);
                stream.Close();
                socketcomein.Close();
            }
            catch (Exception e)
            {
                LogInToEvent.WriteError(e.ToString());
                return;
            }
        }
        private static void readFromConfigureFile()
        {
            setting = new DisableGetObjects.ApplicationSettings();
            LogInToEvent.WriteDebug("读取配置文件");
            setting.ReadFromConfigureFile();
            string i = DisableGetObjects.Log.OverallLog.GetErr();

            LogInToEvent.WriteDebug("读取配置文件完毕");

            LogInToEvent.WriteDebug("记录信息 Info:" + DisableGetObjects.Log.OverallLog.GetLog());
            LogInToEvent.WriteDebug("记录信息 Error:" + i);

            if (i.Trim().Length != 0)
            {
                LogInToEvent.WriteDebug("配置文件错误:\n" + i);
                throw new Exception("读取配置文件过程中出现问题,记录如下:\n" + i);
            }
        }
        /// <summary>
        /// 初始化本程序
        /// </summary>
        public void InitAndStart()
        {
            if (
                settings.FlushTime == 0
                ||
                settings.ItemConfigWoods == null
                ||
                settings.SwitchTypeItems == null
                )
            {
                LogInToEvent.WriteDebug("没有初始化内容");
                throw new Exception("没有初始化内容?");
            }

            //列出待服务队列
            LogInToEvent.WriteDebug("列出待服务队列");
            turnItemIntoList(settings.ItemConfigWoods, ref servList);
            lock (lockServQueue)
            {
                servQueue = new Datastructs.PriorityQueue <Datastructs.Commands.ICommand>();
                foreach (var t in servList)
                {
                    // 约定为DEFAULT_LOW_PRI ,普通的为低优先级
                    servQueue.Enqueue(new Datastructs.Commands.SearchForDisable(t), DEFAULT_LOW_PRI);
                }
            }

            LogInToEvent.WriteDebug("列出待服务队列完成,共" + servList.Count + "项");

            LogInToEvent.WriteDebug("开始初始化线程");
            for (int c = 0; c < pool.Length; ++c)
            {
                pool[c] = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(Scan_DecideIfNeedsScanAndDispatchScan));
                pool[c].Start(c);
            }
            LogInToEvent.WriteDebug("初始化线程结束");

            LogInToEvent.WriteDebug("初始化WEB访问线程");
            itemThredOfWaitWeb = new System.Threading.Thread(new System.Threading.ThreadStart(Web_WaitWebConnection));
            itemThredOfWaitWeb.Start();
            LogInToEvent.WriteDebug("初始化WEB访问线程结束");
        }
 /// <summary>
 /// 用于等待web访问,web访问线程的执行方
 /// </summary>
 void Web_WaitWebConnection()
 {
     System.Net.Sockets.TcpListener listener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Any, PORT);
     try
     {
         listener.Start();
     }
     catch (System.Net.Sockets.SocketException)
     {
         //已经被占用
         LogInToEvent.WriteError("端口" + PORT.ToString() + "已经被占用");
         System.Diagnostics.Process.GetCurrentProcess().Kill();
     }
     while (true)
     {
         var comein  = listener.AcceptTcpClient();
         var dealing = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(Web_AfterConnectionGetReportAndSendToUser));
         dealing.Start(comein);
     }
 }
        /// <summary>
        /// 如果需要的话,调度刷新。刷新线程调度项目
        /// </summary>
        /// <param name="count">当前执行该函数的为第几个线程</param>
        void Scan_DecideIfNeedsScanAndDispatchScan(object count)
        {
            int currItemCount = (int)count;

            while (true)
            {
                try
                {
                    LogInToEvent.WriteDebug("试图取得待操作对象");
                    Datastructs.Commands.ICommand nowUsingItem = null;
                    lock (lockServQueue)
                    {
                        if (!servQueue.IsEmpty())
                        {
                            nowUsingItem = servQueue.Dequeue();
                        }
                    }
                    if (nowUsingItem != null)
                    {
                        lock (lockservItem)
                        {
                            servItem[currItemCount] = nowUsingItem;
                        }

                        //执行操作
                        if (nowUsingItem.IfNeedExecution)
                        {
                            nowUsingItem.DoCommand();
                        }
                        else
                        {
                            System.Threading.Thread.Sleep(1000);
                        }
                        if (nowUsingItem.IsImmuable)
                        {
                            lock (lockServQueue)
                            {
                                servQueue.Enqueue(nowUsingItem, DEFAULT_LOW_PRI);
                            }
                        }
                        lock (lockservItem)
                        {
                            servItem[currItemCount] = null;
                        }
                    }
                    else
                    {
                        //等着看看
                        lock (lockservItem)
                        {
                            servItem[currItemCount] = null;
                        }
                        LogInToEvent.WriteDebug("取得待操作对象失败,休眠100s");
                        System.Threading.Thread.Sleep(100000);
                    }
                }
                catch (Exception e)
                {
                    LogInToEvent.WriteError(e.ToString());
                    DisableGetObjects.Log.OverallLog.LogForErr(e.ToString());
                }
            }
        }