winfrom程序实时更新UI,程序长时间运行,不过我使用的线程和委托运行两天就自动退出了,不知道怎么回事??

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;
using SDWM.DBUtility;
using System.Data.SqlClient;
using System.Threading;
using CarQueueSys.Properties;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace CarQueueSys
{   
    public partial class QueueForm : Form
    {
    
        #region ---------成员变量-------------
            
        private  Thread thread = null;       //刷新绑定的空间数据线程
        private  Thread setGQThread = null;
        private  delegate void Delegate_do();//委托类绑定数据委托
        private  Delegate_do Dele_do;
        private  delegate void Delegate_GQ();
        private  Delegate_GQ Dele_GQ;
        private  Object thisLock;            //线程循环执行锁
        private  bool isConnect = false;     //是否连接数据库     

        #endregion

        #region ------构造函数和加载函数------
        public QueueForm()
        {             
            Control.CheckForIllegalCrossThreadCalls = false; //不捕获对错误线程的调用
            InitializeComponent();
            thisLock = new Object();
            try
            {  
              if (common.Syris_InitComm(1) != 0)                    //连接控制器
                {
                    common.Syris_DelAllIodata(09);                    //清空控制器数据
                    thread = new Thread(new ThreadStart(DoBindData));//绑定数据线程
                    thread.Name ="BindData";
                    thread.IsBackground = true;                       //这样能随主程序一起结束
                    thread.Start(); //开始线程 

                    setGQThread = new Thread(new ThreadStart(DoSetGuoQI));//设置过期
                    setGQThread.Name = "SetGQThread";                  
                    setGQThread.IsBackground = true;                       //这样能随主程序一起结束
                    setGQThread.Start();  //开始线程     
                    timer1.Start();
                }
                else
                {
                    LogRecord.RecordLog("------连接控制器失败,检测控制器是否连接-------");
                }            
            }
            catch (Exception ex)
            {
                LogRecord.RecordLog(ex.Message +ex.Source+ex.InnerException+"------连接控制器失败,检测控制器是否连接-------");
            }
        }   
        #endregion

        #region --------车辆排队逻辑----------

        #region -------------左侧界面内容显示--------  
        /// <summary>
        /// 实时绑定
        /// </summary>
        public void DoBindData()
        {
           
                try
                {
                    while (true)
                    {
                        BindData();
                        Thread.Sleep(8000);
                    }                  
                }
                catch (Exception ex)
                {
                    LogRecord.RecordLog(ex.Message + ex.Source + ex.InnerException + "------数据绑定方法DoBindData-------");
                }
          }
        private void DoSetGuoQI()
        {
             try
                {                  
                    while (true)
                    { 
                        SetGuoQI();
                        Thread.Sleep(8000);                      
                    }                   
                }
                catch (Exception ex)
                {
                    LogRecord.RecordLog(ex.Message + ex.Source + ex.InnerException + "------数据绑定方法DoSetGuoQI-------");
                }         

        }
        /// <summary>
        /// 排队过号设置   过号状态为-1
        /// </summary>
        private void SetGuoQI()
        {
            
                Dele_GQ = SetGuoQI;
                Dele_GQ.BeginInvoke(null, null);
         
                lock (thisLock)
                {
                    try
                    {
                        //查找所有状态为 “请进”的车辆,并判断时间是否超过半小时
                        using (DataSet timeoutDS = SDWM.DBUtility.DbHelperSQL.Query("select VZid,VEndtime,vTid,Vtype from VZHU where Vzhuangt= 1"))
                        {
                             timeoutDS.Dispose();//释放资源
                        }
                    }
                    catch (SqlException ex)
                    {
                        LogRecord.RecordLog(ex.Message + ex.Source + ex.InnerException + "------设置数据过期失败-请检查网络连接!-------");
                    }                  
                }
            
        }//end method
        /// <summary>
        //end method   
        /// <summary>
        /// 绑定灰级别
        /// </summary>       
        private void BindData()//绑定当前车辆正在排队车数量
        {
            if (this.InvokeRequired)
            {
                Dele_do = BindData;
                this.BeginInvoke(Dele_do);
            }
            else
            {
                lock (thisLock)//防止线程死锁
                {
                    try
                    {
                         using (DataSet ds4 = SDWM.DBUtility.DbHelperSQL.Query("select VHID,VHName,VUseable,isVip from VHuiType "))
                        {
                            int count = ds4.Tables[0].Rows.Count;
                            if (count > 0)
                            {
                                for (int i = 0; i < count; i++)
                                {
                                    SetPB(HName, hUseable, VHTypeID, isHvip);
                                    SetLbData(VHTypeID, HName);
                                    Application.DoEvents();
                                }
                            }
                            ds4.Dispose();
                        }
                    }
                    catch (Exception ex)
                    {
                        LogRecord.RecordLog(ex.Message + ex.Source + ex.InnerException + "------数据绑定BindData-------");
                    }
                }
            }
        }     
        /// <summary>
        /// 设置屏幕上显示的按键状态
        /// </summary>
        /// <param name="HuiName"></param>
        /// <param name="isUseable"></param>
        private void SetPB(string HuiName,bool isUseable,string VHTypeID,string vip)
        {
            try
            {               
                switch (HuiName)
                {
                    case "一二期原灰":
                        if (isUseable) { pb1.BackColor = Color.Transparent; }
                        else { pb1.BackColor = Color.Gray; pb1.Enabled = false; }
                        pb1.Enabled = isUseable;
                        pb1.Tag = VHTypeID + "-" + HuiName + "-" + vip; break;

                    case "二期细灰":
                        if (isUseable) { pb2.BackColor = Color.Transparent; }
                        else { pb2.BackColor = Color.Gray; pb2.Enabled = false; }
                        pb2.Enabled = isUseable;
                        pb2.Tag = VHTypeID + "-" + HuiName + "-" + vip; break;

                    case "磨机细灰":
                        if (isUseable) { pb3.BackColor = Color.Transparent; }
                        else { pb3.BackColor = Color.Gray; pb3.Enabled = false; }
                        pb3.Enabled = isUseable;
                        pb3.Tag = VHTypeID + "-" + HuiName + "-" + vip; break;
                    case "三期原灰":
                        if (isUseable) { pb4.BackColor = Color.Transparent; }
                        else { pb4.BackColor = Color.Gray; pb4.Enabled = false; }
                        pb4.Enabled = isUseable;
                        pb4.Tag = VHTypeID + "-" + HuiName + "-" + vip; break;
                    case "三期细灰":
                        if (isUseable) { pb5.BackColor = Color.Transparent; }
                        else { pb5.BackColor = Color.Gray; pb5.Enabled = false; }
                        pb5.Enabled = isUseable;
                        pb5.Tag = VHTypeID + "-" + HuiName + "-" + vip; break;
                    case "三期粗灰":
                        if (isUseable) { pb6.BackColor = Color.Transparent; }
                        else { pb6.BackColor = Color.Gray; pb6.Enabled = false; }
                        pb6.Enabled = isUseable;
                        pb6.Tag = VHTypeID + "-" + HuiName + "-" + vip; break;
                    case "二期粗灰":
                        if (isUseable) { pb7.BackColor = Color.Transparent; }
                        else { pb7.BackColor = Color.Gray; pb7.Enabled = false; }
                        pb7.Enabled = isUseable;
                        pb7.Tag = VHTypeID + "-" + HuiName + "-" + vip; break;
                    default: break;
                }             
            }
            catch(Exception ex)
            {
                LogRecord.RecordLog(ex.Message +ex.Source+ex.InnerException + "------数据绑定SetPB-------");
            }
        }      
        /// <summary>
        /// 根据灰口id获取当前灰车辆等待数量
        /// </summary>
        /// <param name="huiTypeID"></param>
        private void SetLbData(string huiTypeID,string HuiName)
        {
            try
            {              
                PrevoisNum = GetCurrWaitCar(huiTypeID).ToString();
                switch (HuiName)
                {
                    case "一二期原灰":
                        this.lyh.Text = PrevoisNum; break;
                    case "二期细灰":
                        this.lxh.Text = PrevoisNum; break;
                    case "磨机细灰":
                        this.lmj.Text = PrevoisNum; break;
                    case "三期原灰":
                        this.lyh3.Text = PrevoisNum; break;
                    case "三期细灰":
                        this.lxh3.Text = PrevoisNum; break;
                    case "三期粗灰":
                        this.lch.Text = PrevoisNum; break;
                    case "二期粗灰":
                        this.lb2chu.Text = PrevoisNum; break;
                    default: break;
                }                 
            }
            catch (System.Exception ex)
            {
                LogRecord.RecordLog(ex.Message +ex.Source+ex.InnerException + "------数据绑定SetLbData-------");               
            }
        }
        /// <summary>
        /// 根据灰口号获取当前灰口等待的车辆
        /// </summary>
        /// <param name="id"></param>  
        private int GetCurrWaitCar(string HTypeid)
        {
            try
            {
                return Convert.ToInt32(DbHelperSQL.GetSingle("select count(VZid) from VZHU  where  Vzhuangt in( 0 ,1 ,2 ,4 ,7)  and  Vtype='" + HTypeid + "'"));
            }
            catch (Exception ex)
            {
                LogRecord.RecordLog(ex.Message +ex.Source+ex.InnerException + "------数据绑定GetCurrWaitCar-------");
                return 0;
            }         
        }
        #endregion 

        #region --------连接控制器并开始循环读卡---------

        byte[] status = new byte[100];
        byte[] status2 = new byte[100];
        byte[] status1 = new byte[3];
        byte[] statuse = new byte[10];
        byte[] status2e = new byte[10];
        byte[] byte3 = new byte[10];

        string strIDs = "";
        string strGetEPCid = "";       
        object result = null;       
        string currTid = string.Empty;
        string vipstarttime = "";
        string vipendtime = "";
        string vipType="";
        string huiList="";
        /// <summary>
        /// 控制器 循环读卡
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                if (!isConnect)
                {    
                    return;
                }              
                //读取控制器中卡数据
                strGetEPCid = string.Empty;
                common.Syris_PollIodata(09, status);
                strIDs = System.Text.Encoding.ASCII.GetString(status);
                status1[0] = (byte)Convert.ToChar(strIDs.Substring(39, 1));
                status1[1] = (byte)Convert.ToChar(strIDs.Substring(40, 1));
                common.Syris_ReadCardID(09, status1, status2);
                strGetEPCid = System.Text.Encoding.ASCII.GetString(status2);
                common.Syris_DelOneIodata(09);
                common.Syris_DelAllIodata(09);
                if (strGetEPCid != "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0")
                {
                    currTid = strGetEPCid.Substring(10, 4);                                      
                    if (currTid != "0000" && currTid.Contains("C"))
                    {
                        #region 卡片数据操作
                        //通过该标签的EPC数据检索数据库对应的数据
                        using (DataSet ds = SDWM.DBUtility.DbHelperSQL.Query("select VLicense,VUName,VipLevel,viptype,vipstarttime,vipendtime,vipHuiStr from Vehicles where VTid='" + currTid + "'"))
                        {
                            if (ds.Tables[0].Rows.Count <= 0)
                            {
                                ds.Dispose();
                                ResetLb();                              
                                return;
                            }
                            else
                            {
                                result = SDWM.DBUtility.DbHelperSQL.GetSingle("select count(*) from VZHU where Vzhuangt in(2,4,6) and vTid='" + currTid + "'");
                                if (result.ToString() != "0")
                                {
                                    //非法排队
                                    ds.Dispose();
                                    ResetLb();                                 
                                    return;
                                }
                                //显示数据在触摸屏上
                                lbCarNo.Text = ds.Tables[0].Rows[0]["VLicense"].ToString();
                                lbOwner.Text = ds.Tables[0].Rows[0]["VUName"].ToString();
                                lbData.Text = DateTime.Now.ToLocalTime().ToShortDateString();
                                lbTime.Text = DateTime.Now.ToLocalTime().ToLongTimeString();
                                vipLevel = Convert.ToInt32(ds.Tables[0].Rows[0]["VipLevel"].ToString());//一级vip还是二级vip
                                vipType = ds.Tables[0].Rows[0]["viptype"].ToString();//vip类型 一次性vip还是永久
                                huiList = ds.Tables[0].Rows[0]["vipHuiStr"].ToString();//一次性VIP可以排队的灰口
                                if (vipType == "1" && vipLevel == 1)//只针对一次性VIP 进行时间段内判定
                                {
                                    try
                                    {
                                        if (ds.Tables[0].Rows[0]["vipstarttime"] != null && ds.Tables[0].Rows[0]["vipendtime"] != null)
                                        {
                                            vipstarttime = ds.Tables[0].Rows[0][4].ToString();//vip开始时间
                                            vipendtime = ds.Tables[0].Rows[0][5].ToString();//vip结束时间
                                            DateTime starttime = Convert.ToDateTime(vipstarttime);
                                            DateTime endtime = Convert.ToDateTime(vipendtime);
                                            TimeSpan ts = DateTime.Now.Subtract(starttime);//获取最新更新时间      
                                            TimeSpan te = DateTime.Now.Subtract(endtime);
                                            if (ts.TotalMinutes < 0 || te.TotalMinutes > 0)
                                            {
                                                vipLevel = 0;//不在时间段内,只能当作普通车辆
                                            }
                                        }
                                    }
                                    catch
                                    {
                                    }//end 时间判定
                                }
                                //判断是否已排队
                                result = SDWM.DBUtility.DbHelperSQL.GetSingle("select count(*) from VZHU where Vzhuangt in(0,1,7) and vTid='" + currTid + "'");
                                if (result.ToString() == "0")//当前车辆没有正在请进或者等待的排队的信息
                                {
                                    //判断时间是否在允许范围内 默认重新排队时间是2小时
                                    if (vipLevel == 0 || vipLevel == 2)// 一级vip不做时间限制
                                    {
                                        if (!isAllowQueue(currTid))
                                        {
                                            ds.Dispose();
                                            ResetLb();
                                            lbErrorMsg.Text = "提醒:您排队过于频繁,请按照规定 " + reQueueTime + " 小时后再次排队 !";
                                           
                                            return;
                                        }
                                    }//end method
                                    #region 如果显示触摸屏数据,信号灯显示为绿色 执行下面代码
                                    OpenLight();//开启红绿灯
                                    #endregion
                                    timer1.Stop();
                                    SetAllPB(true);
                                    lbErrorMsg.Text = "";
                                    this.lbBianMa.Text = MakeStr(SDWM.DBUtility.DbHelperSQL.GetSingle("select VDaij from SConfig where Type='6'").ToString());
                                    this.btnReQueue.Enabled = false;//禁用重新排队
                                    this.btnReQueue.BackColor = Color.Gray;
                                    ds.Dispose();
                                    common.Syris_DelAllIodata(09);
                                }
                                else
                                {
                                    #region 如果显示触摸屏数据,信号灯显示为绿色 执行下面代码
                                    OpenLight();//开启红绿灯
                                    #endregion
                                    SetAllPB(false);
                                    btnReQueue.Enabled = true;
                                    btnReQueue.BackColor = Color.Transparent;
                                    ds.Dispose();
                                    common.Syris_DelAllIodata(09);
                                    lbErrorMsg.Text = "提醒:您已排队,如果想重新排队,请点击[重新排队]按键!";
                                }
                            }
                        }
                        #endregion         
                    }
                    else
                    {
                        ResetLb();
                    }
                }
                else
                {
                    ResetLb();
                }
            }
            catch(Exception ex)
            {
                LogRecord.RecordLog(ex.Message +ex.Source+ex.InnerException + "-----实时获取卡片信息timer1_Tick");
            }
            finally
            {   
                System.GC.Collect();
            }
        }
        //判断是否可以进行再次排队 
        private bool isAllowQueue(string Tid)
        {
            try
            {
                object reuslt = SDWM.DBUtility.DbHelperSQL.GetSingle(" select count(*) from VZHU where Vzhuangt !=-2 and Vzhuangt !=-1  and vTid='" + Tid + "'");
                if (reuslt.ToString() != "0")
                {
                    object time = SDWM.DBUtility.DbHelperSQL.GetSingle("select top(1) VEndtime from VZHU where Vzhuangt !=-2 and Vzhuangt !=-1 and vTid='" + Tid + "'order by VEndtime desc");
                    DateTime lastTime = Convert.ToDateTime(time);//获取最新更新时间              
                    TimeSpan ts = DateTime.Now.Subtract(lastTime);
                    if (ts.TotalHours >= reQueueTime)
                    {
                       return true;
                    }
                    else
                    {
                       return false;
                    }
                }
                else
                {
                    return true;
                }
            }
            catch(Exception ex)
            {
                LogRecord.RecordLog(ex.Message +ex.Source+ex.InnerException+"是否允许排队");
                throw ex;
            }
        }
        //开启红绿灯
        private void OpenLight()
        {
            try
            {
                //--控制器、绿灯开启
                byte3[0] = (byte)'1';
                statuse[0] = (byte)'2';
                status2e[0] = (byte)'0';
                status2e[1] = (byte)'0';
                status2e[2] = (byte)'1';
                status2e[3] = (byte)'5';
                common.Syris_ImmOpenDoor(09, statuse, status2e);
                common.Syris_ImmOpenDoor(09, byte3, status2e);
            }
            catch(Exception ex)
            {
                LogRecord.RecordLog(ex.Message +ex.Source+ex.InnerException+"-----打开红绿灯");
            }
        }
        //设置界面按键可用状态
        private void SetAllPB(bool isAble)
        {
            try
            {
                if (isAble)
                {
                    pb1.Click += new EventHandler(pb2_Click);
                    pb2.Click += new EventHandler(pb2_Click);
                    pb3.Click += new EventHandler(pb2_Click);
                    pb4.Click += new EventHandler(pb2_Click);
                    pb5.Click += new EventHandler(pb2_Click);
                    pb6.Click += new EventHandler(pb2_Click);
                    pb7.Click += new EventHandler(pb2_Click);
                }
                else
                {
                    pb1.Click -= new EventHandler(pb2_Click);
                    pb2.Click -= new EventHandler(pb2_Click);
                    pb3.Click -= new EventHandler(pb2_Click);
                    pb4.Click -= new EventHandler(pb2_Click);
                    pb5.Click -= new EventHandler(pb2_Click);
                    pb6.Click -= new EventHandler(pb2_Click);
                    pb7.Click -= new EventHandler(pb2_Click);
                }
                pb1.Enabled = isAble;
                pb2.Enabled = isAble;
                pb3.Enabled = isAble;
                pb4.Enabled = isAble;
                pb5.Enabled = isAble;
                pb6.Enabled = isAble;
                pb7.Enabled = isAble;
            }
            catch(Exception ex)
            {
                LogRecord.RecordLog(ex.Message +ex.Source+ex.InnerException + "-----设置按键状态SetAllPB");
            }
        }
      
        #endregion

        #region -------------打印小票信息代码-------------

        /// <summary>
        /// 打印小票信息 参数有
        /// </summary>
        /// <param name="CarNum">前面等待的车辆数</param>
        /// <param name="currTime">当前取票时间</param>
        /// <param name="chepai">车牌号码</param>
        /// <param name="huiType">灰级别</param>
        /// <param name="huikou">灰口号</param> 
        PrintPreviewDialog ppd =null;
        PrintDocument pd = null;
        Margins margin = null;
        PaperSize pageSize = null;
        private void PrintBill()
        {
            try
            {
                //此处编写打印代码
                //打印预览 
                ppd = new PrintPreviewDialog();
                pd = new PrintDocument();
                //设置边距
                margin = new Margins(10, 10, 10, 10);
                pd.DefaultPageSettings.Margins = margin;
                ////纸张设置默认
                pageSize = new PaperSize("First custom size", getYc(20.3), 20);
                pd.DefaultPageSettings.PaperSize = pageSize;
                //打印事件设置 
                pd.PrintPage += new PrintPageEventHandler(printDocument_PrintPage);
                pd.Print();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message +ex.Source+ex.InnerException, "未安装打印机!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                pd.PrintController.OnEndPrint(pd, new PrintEventArgs());
            }          
            finally
            {  
                ppd.Dispose(); 
                pd.Dispose();            
            }
        }
        private void printDocument_PrintPage(object sender, PrintPageEventArgs e)
        {
            //通过GDI+绘制打印文档 
            e.Graphics.DrawString(GetPrintStr(), new Font("宋体", 12.0f), Brushes.Black, 5, -1);
        }
        //计算 宽度
        private int getYc(double cm)
        {
            return (int)(cm / 25.4) * 100;
        }
        /// <summary>
        ///获取打印字符串
        /// </summary>
        /// <returns></returns>
        /// <param name="carNum">前面等待的车辆数</param>
        /// <param name="currTime">当前取票时间</param>
        /// <param name="chepai">车牌号码</param>
        /// <param name="huiType">灰级别</param>
        /// <param name="huikou">灰口号</param>  
        StringBuilder sb = null;
        private string GetPrintStr()
        {
            sb = new StringBuilder();
            try
            {
                sb.Append("      国电石横电厂      \n");
                sb.Append("---------------------------------------\n");
                sb.Append("取票时间:" + this.lbData.Text + " " + this.lbTime.Text + "\n");
                sb.Append("---------------------------------------\n");
                sb.Append("车牌号: " + this.lbCarNo.Text + "  " + "编号:" + this.lbBianMa.Text + "\n");
                sb.Append("\n");
                sb.Append("前面等待车辆:" + currWaitCarNum + "辆\n");
                sb.Append("\n");
                sb.Append("灰类型:" + currTypeName + "\n");
                sb.Append("\n");
                sb.Append("序号:" + this.lbXhao.Text + "\n");
                sb.Append("----------------------------------------\n");
                sb.Append("  谢谢惠顾,欢迎您下次光临 ! ");
                return sb.ToString();
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            finally
            {
                sb = null;
            }
           
        }

        #endregion

        #region ---------用户选择相应的灰级别信息并打印-----------  
        string[] huiData;
        string[] huiLists;
        private void pb2_Click(object sender, EventArgs e)
        {   
            PictureBox currPB = (PictureBox)sender;
            huiData = null;
            huiLists = null;
            try
            {              
                if (lbCarNo.Text == "" || lbBianMa.Text == "" || currPB.BackColor == Color.Gray)
                {
                    return;
                }
               
                currPB.BorderStyle = BorderStyle.Fixed3D;
                if (currPB.Tag.ToString() != "")
                {
                    huiData = currPB.Tag.ToString().Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries);
                    if (huiData.Length <= 0)
                    {
                        return;
                    }
                    currHTypeID = huiData[0];
                    currTypeName = huiData[1];
                    currWaitCarNum = GetCurrWaitCar(huiData[0]);   //获取灰级别前面等待车辆

                   
                    //限制VIP车辆排队灰口,只针对VIP
                    if (vipLevel != 0)
                    {
                        bool canQueue = false;
                        huiLists = huiList.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (string hui in huiLists)
                        {
                            if (hui == currHTypeID)//是否是运行进行一级VIP排队的
                            {
                                canQueue = true;
                                break;
                            }
                        }
                        if (!canQueue)
                        {
                            vipLevel = 0;
                        }
                    }
                    #region --------------根据vip级别 生成排队虚编号-------------
                    if (vipLevel == 1)//一级vip排队
                    {
                        currHBM = -1;
                        currXBM = CreateXubian(-1, Convert.ToInt32(currHTypeID), Inveval);
                        lbXhao.Text = MakeHXStr(currHTypeID, vipLevel);
                    }
                    else if (vipLevel == 2)//二级vip排队
                    {
                        currHBM = 0;
                        currXBM = CreateXubian(0, Convert.ToInt32(currHTypeID), Inveval);
                        lbXhao.Text = MakeHXStr(currHTypeID, vipLevel);
                    }
                    else//普通用户排队
                    {
                        if (huiData[2] == "1")//如果不是vip专用灰口
                        {
                            currXBM = CreateXubian(1, Convert.ToInt32(currHTypeID), Inveval);
                            currHBM = Convert.ToInt32(currXBM) / 100;
                            this.lbXhao.Text = MakeHXStr(currHTypeID, vipLevel);
                        }
                        else
                        {
                            //如果是vip专用口 不执行
                            lbErrorMsg.Text = "此灰口暂时不开放,请更换!";
                            ResetLb();                          
                            timer1.Start();
                            return;
                        }
                    }
                    #endregion
                    ///打印当前信息
                    if (MessageBox.Show("您是否确定要进入排队", "打印提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.No)
                    {
                        ResetLb();                        
                        timer1.Start();
                        return;
                    }
                    else
                    {
                        updateData();//往数据库更新数据,并打印
                        BindData();
                        System.GC.Collect();               
                    }
                }
            }
            catch(Exception ex) 
            {
                LogRecord.RecordLog(ex.Message +ex.Source+ex.InnerException+"-----点击按键排队");
            }
            finally
            {                     
                System.GC.Collect();
            }
           
        }
        /// <summary>
        /// 当用户点击选择时,打印小票
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        StringBuilder strSql = null;
        private void updateData()
        {
            try
            {
                //将记录写入当天的数据表中 
                strSql = new StringBuilder();
                strSql.Append("insert into VZHU(");
                strSql.Append("vTid,Vtype,Vzhuangt,VStrtime,VEndtime,VXhao,VBianMa,VHXhao,VHAll,VX)");
                strSql.Append(" values (");
                strSql.Append("@vTid,@Vtype,@Vzhuangt,@VStrtime,@VEndtime,@VXhao,@VBianMa,@VHXhao,@VHAll,@VX)");
                strSql.Append(";select @@IDENTITY");
                SqlParameter[] parameters = {
                    new SqlParameter("@vTid",     SqlDbType.VarChar,50),
                    new SqlParameter("@Vtype",    SqlDbType.VarChar,50),
                    new SqlParameter("@Vzhuangt", SqlDbType.Int,4),
                    new SqlParameter("@VStrtime", SqlDbType.DateTime,8),
                    new SqlParameter("@VEndtime", SqlDbType.DateTime,8),
                    new SqlParameter("@VXhao",    SqlDbType.VarChar,50),
                    new SqlParameter("@VBianMa",  SqlDbType.Int,4),
                    new SqlParameter("@VHXhao",   SqlDbType.Int,4),
                    new SqlParameter("@VHAll",    SqlDbType.Int,4),
                    new SqlParameter("@VX",       SqlDbType.VarChar,50)
                                      };
                parameters[0].Value = currTid;
                parameters[1].Value = currHTypeID;
                parameters[2].Value = "0";
                parameters[3].Value = DateTime.Now.ToLocalTime();
                parameters[4].Value = DateTime.Now.ToLocalTime();
                parameters[5].Value = this.lbBianMa.Text;
                parameters[6].Value = currXBM;//排队编码例如 240
                parameters[7].Value = currHBM;//灰口编码     1
                parameters[8].Value = isTongZhuang(currHTypeID);
                parameters[9].Value = this.lbXhao.Text.Trim();//LED第一列 显示序号
                int obj = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
                if (obj > 0)
                {
                    SDWM.DBUtility.DbHelperSQL.ExecuteSql("update SConfig set VDaij ='" + lbBianMa.Text + "' where Type='6'");
                    carStatus(currHTypeID);//判断是否厂区外有提升的车辆               
                    //PrintBill();    //打印小票 前面等待人数,当前系统时间,当前车牌,选择灰级别,当前灰口-------------------------------暂停打印功能------------------------------
                }    
                ResetLb();
                Application.DoEvents(); 
                common.Syris_DelAllIodata(09);             
                parameters = null;
                strSql = null;
                timer1.Start();
            }
            catch (Exception ex)
            {
                LogRecord.RecordLog(ex.Message +ex.Source+ex.InnerException+"---------排队完成后更新数据库信息");
               
            }           
        } 
        /// <summary>
        /// 生成vip虚编码
        /// </summary>
        /// <param name="VHXhao">当前灰排队编号 -1是一级vip 0是二级vip</param>
        /// <param name="Vtype">灰型id</param>
        /// <param name="InvevalNum">vip间隔</param>
        /// <returns>生成排队编码</returns
        private string CreateXubian(int VHXhao, int Vtype, int InvevalNum)
        {
            try
            {
                SqlParameter[] parameters = {
                    new SqlParameter("@VHXhao", SqlDbType.Int,4),
                    new SqlParameter("@Vtype", SqlDbType.Int,4),
                    new SqlParameter("@VInvevalNum", SqlDbType.Int,4),
                    new SqlParameter("@VBianMa", SqlDbType.Int,4)
                                            };
                parameters[0].Value = VHXhao;//
                parameters[0].Direction = ParameterDirection.Input;
                parameters[1].Value = Vtype;
                parameters[1].Direction = ParameterDirection.Input;
                parameters[2].Value = InvevalNum;
                parameters[2].Direction = ParameterDirection.Input;
                parameters[3].Direction = ParameterDirection.Output;
                SDWM.DBUtility.DbHelperSQL.RunProcedure("CreateBianma", parameters);
                return parameters[3].Value.ToString();
            }
            catch(Exception ex)
            {
                LogRecord.RecordLog(ex.Message +ex.Source+ex.InnerException+"------生成排队编码");
                return "0";
            }           
        }
        //判断当前灰型是否通装       
        private string isTongZhuang(string huiTypeID)
        {
            try
            {
                boolSql = "SELECT Useable FROM  FHuiType WHERE id IN (SELECT FHuiID FROM VHuiType WHERE VHID='" + huiTypeID + "')";
                if (SDWM.DBUtility.DbHelperSQL.GetSingle(boolSql) != null)
                {
                    isTongZ = SDWM.DBUtility.DbHelperSQL.GetSingle(boolSql).ToString();
                    return isTongZ;
                }
                else
                {
                    return "1";//1表示不可以统装,0表示不可以统装
                }
            } 
            catch(Exception ex)
            {
                LogRecord.RecordLog(ex.Message +ex.Source+ex.InnerException+"---是否统装");
                throw ex;
            }
        }       
        /// <summary>        
        /// </summary>
        /// <param name="htypeID"></param>
        //设置灰口排队车辆状态前进
        private void carStatus(string htypeID)
        {
            try
            {
                //父级灰id
                string huiFjID = SDWM.DBUtility.DbHelperSQL.GetSingle("select FHuiID from VHuiType where VHID='" + htypeID + "'").ToString();//原始灰机
                //判断当前灰类是否处于等待模式
                string res = SDWM.DBUtility.DbHelperSQL.GetSingle("select isWaitMode from FHuiType where id='" + huiFjID + "'").ToString();
                if (res == "1")//如果处于等待模式,不进行任何操作 如果不处于等待模式,则进行下一个车辆更新为请进
                {
                    boolSql = "select maxCar from VHuiType where VHID='" + htypeID + "' and maxCar <= (select count(*) from VZHU  where Vzhuangt>=1 and Vzhuangt <5 and Vtype='" + htypeID + "')";
                    if (SDWM.DBUtility.DbHelperSQL.GetSingle(boolSql) == null)
                    {
                        object sql = SDWM.DBUtility.DbHelperSQL.GetSingle("select top(1) vzid from VZHU where Vzhuangt=0 and Vtype='" + htypeID + "' order by VBianMa asc");
                        if (sql != null)
                        {
                            SDWM.DBUtility.DbHelperSQL.ExecuteSql("update VZHU set Vzhuangt='1' ,VEndtime= '" + DateTime.Now.ToLocalTime() + "' where Vzhuangt='0' and Vtype='" + htypeID + "'and vzid='" + sql.ToString() + "'");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogRecord.RecordLog(ex.Message +ex.Source+ex.InnerException+"----车辆状态设置");
             
            }
            finally
            {
                htypeID = null;
            }
        }
        #endregion

        #region------------生成排队号码和其他操作---------------- 
        #region 生成字符串的灰口排队号
        string NewNo = string.Empty;
        int len;
        //生成编码
        private string MakeStr(string curStr)
        {
            try
            {
                NewNo = string.Empty;
                NewNo = (Convert.ToInt32(curStr) + 1).ToString();
                len = NewNo.Length;
                if (len <= 5)
                {
                    for (int i = 0; i < 5 - len; i++)
                    {
                        NewNo = "0" + NewNo;
                    }
                }
                else
                {
                    NewNo = "00001";
                    SDWM.DBUtility.DbHelperSQL.ExecuteSql("update SConfig set VDaij='00001' where Type='6'");
                }
                return NewNo;
            }
            catch (Exception ex)
            {
                LogRecord.RecordLog(ex.Message +ex.Source+ex.InnerException+"---------生成编码");
                throw ex;
            }
        }
        //生成显示序号
        private string MakeHXStr(string typeID,int level)
        {
           
                object maxVX;
                NewNo = string.Empty;
                try
                {
                    if (level == 1)//一级VIP设置
                    {
                        maxVX = SDWM.DBUtility.DbHelperSQL.GetSingle("select top(1) VX  from VZHU where Vtype='" + typeID + "' and VHXhao=-1 order by Vstrtime desc");
                        if (maxVX != null)
                        {
                            NewNo = (Convert.ToInt32(maxVX) + 1).ToString();
                            len = NewNo.Length;
                            if (len <= 3)
                            {
                                for (int i = 0; i < 3 - len; i++)
                                {
                                    NewNo = "0" + NewNo;
                                }
                            }
                            if (NewNo.Substring(1, 2) != "00")
                            {
                                NewNo = "1" + NewNo.Substring(1, 2);
                            }
                            else
                            {
                                NewNo = "101";
                            }
                        }
                        else
                        {
                            NewNo = "101";
                        }
                    }
                    else if (level == 2)
                    {
                        maxVX = SDWM.DBUtility.DbHelperSQL.GetSingle("select top(1) VX  from VZHU where Vtype='" + typeID + "' and VHXhao=0 order by Vstrtime desc");
                        if (maxVX != null)
                        {
                            NewNo = (Convert.ToInt32(maxVX) + 1).ToString();
                            len = NewNo.Length;
                            if (len <= 3)
                            {
                                for (int i = 0; i < 3 - len; i++)
                                {
                                    NewNo = "0" + NewNo;
                                }
                            }
                            if (NewNo.Substring(1, 2) != "00")
                            {
                                NewNo = "2" + NewNo.Substring(1, 2);
                            }
                            else
                            {
                                NewNo = "201";
                            }
                        }
                        else
                        {
                            NewNo = "201";
                        }
                    }
                    else
                    {
                        maxVX = SDWM.DBUtility.DbHelperSQL.GetSingle("select top(1) VX  from VZHU where Vtype='" + typeID + "' and VHXhao >0 order by Vstrtime desc");
                        if (maxVX != null)
                        {
                            NewNo = (Convert.ToInt32(maxVX) + 1).ToString();
                            len = NewNo.Length;
                            if (len <= 3)
                            {
                                for (int i = 0; i < 3 - len; i++)
                                {
                                    NewNo = "0" + NewNo;
                                }
                            }
                            if (NewNo.Substring(1, 2) != "00")
                            {
                                NewNo = "0" + NewNo.Substring(1, 2);
                            }
                            else
                            {
                                NewNo = "001";
                            }
                        }
                        else
                        {
                            NewNo = "001";
                        }
                    }
                   return NewNo;
                }
                catch(Exception ex)
                {
                    LogRecord.RecordLog(ex.Message +ex.Source+ex.InnerException + "------灰口序号MakeHXStr");
                    throw ex;
                }              
           
        }
        #endregion

        private void pb2_MouseClick(object sender, MouseEventArgs e)
        {
            try
            {
                PictureBox currPB = (PictureBox)sender;
                currPB.BorderStyle = BorderStyle.None;
            }
            catch (Exception ex)
            {
                LogRecord.RecordLog(ex.Message +ex.Source+ex.InnerException+"----样式设置");
            }
        }               
        //清空界面显示
        private void ResetLb()
        {
            try
            {
                strGetEPCid = null;
                currTid = "";
                lbCarNo.Text = "";
                lbData.Text = "";
                lbOwner.Text = "";
                lbBianMa.Text = "";
                lbTime.Text = "";
                lbXhao.Text = "";
                lbErrorMsg.Text = "";
                common.Syris_DelOneIodata(09);
                common.Syris_DelAllIodata(09);
                System.GC.Collect();
            }
            catch(Exception ex)
            {
                LogRecord.RecordLog(ex.Message +ex.Source+ex.InnerException + "----清空显示");
            }
        }
        //重新排队 重新排队的状态为-2
        private void btnReQueue_Click(object sender, EventArgs e)
        {
            //删除当前排队信息 
            try
            {
                if (currTid != "" && this.lbCarNo.Text != "")
                {
                    if (MessageBox.Show("您是否确定要重新排队?","重新排队提示",MessageBoxButtons.YesNo,MessageBoxIcon.Warning)== DialogResult.Yes)
                    {
                        carStatusSet(currTid, currHTypeID);//从新排队,更改状态 
                        SDWM.DBUtility.DbHelperSQL.ExecuteSql("update VZHU set Vzhuangt='-2',VEndtime='" + DateTime.Now.ToLocalTime() + "' where  vTid='" + currTid + "'and (Vzhuangt='0' or Vzhuangt='1' or Vzhuangt='7')");
                        ResetLb();
                        lbErrorMsg.Text = "";
                    }
                }
                BindData();
                common.Syris_DelAllIodata(09);
                timer1.Start();
            }
            catch(Exception ex)
            {
                LogRecord.RecordLog(ex.Message +ex.Source+ex.InnerException + "----重新排队");               
            }
        }
        //让下一辆车处于 请进状态
        private void carStatusSet(string tid,string htypeID)
        {
            lock (thisLock)
            {
                try
                {
                    using (DataSet ds1 = SDWM.DBUtility.DbHelperSQL.Query("select Vtype,VXhao,VBianMa from VZHU where Vzhuangt='1' and vTid='" + tid + "'"))
                    {
                        if (ds1.Tables[0].Rows.Count <= 0)
                        {
                            ds1.Dispose();
                            return;
                        }
                        else
                        {
                            //父级灰id
                            string huiFjID = SDWM.DBUtility.DbHelperSQL.GetSingle("select FHuiID from VHuiType where VHID='" + htypeID + "'").ToString();//原始灰机
                            //判断当前灰类是否处于等待模式
                            string res = SDWM.DBUtility.DbHelperSQL.GetSingle("select isWaitMode from FHuiType where id='" + huiFjID + "'").ToString();
                            if (res == "1")//如果处于等待模式,不进行任何操作 如果不处于等待模式,则进行下一个车辆更新为请进
                            {
                                boolSql = "select maxCar from VHuiType where VHID='" + htypeID + "' and maxCar <= (select count(*) from VZHU  where Vzhuangt>=1 and Vzhuangt <5 and Vtype='" + htypeID + "'and vTid !='" + tid + "')";
                                if (SDWM.DBUtility.DbHelperSQL.GetSingle(boolSql) == null)
                                {
                                    object sql = SDWM.DBUtility.DbHelperSQL.GetSingle("select top(1) vzid from VZHU where Vzhuangt=0 and Vtype='" + htypeID + "' order by VBianMa asc");
                                    if (sql != null)
                                    {
                                        SDWM.DBUtility.DbHelperSQL.ExecuteSql("update VZHU set Vzhuangt='1' ,VEndtime= '" + DateTime.Now.ToLocalTime() + "' where Vzhuangt='0' and Vtype='" + htypeID + "'and vzid='" + sql.ToString() + "'");
                                    }
                                }
                            }
                            ds1.Dispose();
                        }
                    }

                }
                catch (Exception ex)
                {
                    LogRecord.RecordLog(ex.Message + ex.Source + ex.InnerException + "----设置车辆排队状态");                   
                }
            }
        }
        //重新获取卡号
        private void btnReGet_Click(object sender, EventArgs e)
        {
            try
            {
                ResetLb();
                lbErrorMsg.Text = ""; 
                common.Syris_DelAllIodata(09);
                timer1.Start();
               
            }
            catch (Exception ex)
            {
                LogRecord.RecordLog(ex.Message +ex.Source+ex.InnerException + "----重新获取卡号");
            }

        }
        #endregion 
        #endregion        

        #region -----------内存优化-----------
        /// <summary>
        /// 将当前进程的内存占用尺寸设置到最小
        /// </summary>
        /// <returns>0为成功,-1为失败</returns>
        public static int SetProcessMemoryToMin()
        {
            return SetProcessMemoryToMin(Process.GetCurrentProcess().Handle);
        }
        /// <summary>
        /// 将内存占用尺寸设置到最小
        /// </summary>
        /// <param name="SetProcess">需要设置内存使用范围的程序进程句柄,一般为当前进程, 如:System.Diagnostics.Process.GetCurrentProcess().Handle</param>
        /// <returns>0为成功,-1为失败</returns>
        public static int SetProcessMemoryToMin(IntPtr SetProcess)
        {
            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                return SetProcessWorkingSetSize(SetProcess, -1, -1);
            }
            else
            {
                return -1;
            }
        }

        [DllImport("kernel32.dll")]
        private static extern int SetProcessWorkingSetSize(IntPtr hProcess, int dwMinimumWorkingSetSize, int dwMaximumWorkingSetSize);

        #endregion

    }
}

  

posted @ 2013-01-16 19:02  Devil_jim  阅读(3858)  评论(0编辑  收藏  举报