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

    }
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM