1. 程式人生 > >多執行緒進度條顯示

多執行緒進度條顯示

       //進度條所需變數

        private int IsSucess = -1;//判斷資料庫操作是否成功

        public delegate int ProcessDataDelegate(string buildID);

        public BuildEnergyEx()
        {
            InitializeComponent();
            this.gvList.AutoGenerateColumns = false;
            this.gvList.AllowUserToAddRows = false;
            BindData(currentPage);
        }


        /// <summary>
        /// 響應刪除,忽略按鈕事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gvList_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (this.gvList.Columns[e.ColumnIndex].Name == "btnDel")

            {

             //開啟多執行緒呼叫進度條

                IsSucess = -1;
                processingBuildID = this.gvList.Rows[e.RowIndex].Cells["BuildID"].Value.ToString();

                ProcessDataDelegate d1 = processData;
                IAsyncResult ar = d1.BeginInvoke(processingBuildID, null, null);
                //while (!ar.IsCompleted)
                //{
                //}
                //int result = d1.EndInvoke(ar);

                ProcessOperator process = new ProcessOperator();
                process.MessageInfo = "正在拼命處理中,請稍候...";
                process.BackgroundWork = this.Do;
                process.BackgroundWorkerCompleted += new EventHandler<BackgroundWorkerEventArgs>(process_BackgroundWorkerCompleted);
                process.Start();
            }
        }

     //委託方法

        int processData(string buildid)
        {
            //進行能耗資料的更新
            return IsSucess = BuildOperatorBLL.GetDataCorrectByID(processingBuildID);
        }

        #region 增加進度條
        void process_BackgroundWorkerCompleted(object sender, BackgroundWorkerEventArgs e)
        {
            if (e.BackGroundException == null)
            {
                BindData(currentPage);
                MessageBox.Show("執行完畢");
            }
            else
            {
                MessageBox.Show("異常:" + e.BackGroundException.Message);
            }
        }

        void Do()
        {
            while (IsSucess < 0)
            {
                Thread.Sleep(20);
            }
        }

        #endregion