[C#]使用BackgroudWorker刷新UI延迟的解决方法

今天使用BackgroundWorker刷新UI发生延时现象,找了好久才发现AutoResetEvent可以解决,代码如下

        private void BgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            int i = e.ProgressPercentage;
            var str = "{'parameter':{'items':[{'lotId':'" + lstbar.Items[i] + "','parameterSeq':'0','parameterId':'FLD_GRADE','parameterValue':'A'}],'collectionType':'BY_LOT'}}";
            var s = mes.dispatchLotForFR("M18", txtUserName.Text, txtDeviceName.Text.Trim(), "["" + lstbar.Items[i] + ""]", str, false);
            JObject jObject = (JObject)JsonConvert.DeserializeObject(s, jSettitng);
            bool success = Convert.ToBoolean(jObject["success"]);
            string msg = jObject["msg"].ToString();
            lblDetail.Text = msg;
            try
            {
                //记录MES过站
                LotInfo lot = new LotInfo();
                if (success)
                {
                    lot.Success = true;
                    lblResult.Text = "过站成功";
                    lblResult.ForeColor = Color.Blue;
                    lblOK.Text = (++iNumOk).ToString();
                    iWorkerOK++;
                    WriteListBoxToFile(string.Format("组件序列号[{0}]过站[成功]消息[{1}],成功总计:[{2}]", lstbar.Items[i], msg,iNumOk));
                }
                else
                {
                    lot.Success = false;
                    lblResult.Text = "过站失败";
                    lblResult.ForeColor = Color.Red;
                    lblNG.Text = (++iNumNG).ToString();
                    iWorkerNG++;
                    WriteListBoxToFile(string.Format("组件序列号[{0}]过站[失败]消息[{1}],失败总计[{2}]", lstbar.Items[i], msg,iNumNG));
                    sbNG.AppendLine(lstbar.Items[i].ToString());
                }

                lot.LotNo = lstbar.Items[i].ToString();
                //直接用设备号
                //lot.DeviceNo= txtDeviceName.Text.Substring(4, 1) + txtDeviceName.Text.Substring(8, 2);
                lot.DeviceNo = txtDeviceName.Text.Trim();
                lot.Msg = msg;
                lot.CreateTime = DateTime.Now;
                if (tSet.IsInsertDb)
                {
                    int k = lot.InsertDispatchLot(lot);
                    if (k > 0)
                    {
                        WriteListBoxToFile(string.Format("写入MES数据库成功,序列号:[{0}],设备号:[{1}],Success:[{2}],Msg:[{3}],时间:[{4}]", lot.LotNo, lot.DeviceNo, lot.Success, lot.Msg, lot.CreateTime));
                    }
                    else
                    {
                        WriteListBoxToFile(string.Format("写入MES数据库失败,序列号:[{0}],设备号:[{1}],Success:[{2}],Msg:[{3}],时间:[{4}]", lot.LotNo, lot.DeviceNo, lot.Success, lot.Msg, lot.CreateTime));
                        log.WriteExceptionLog(string.Format("写入MES数据库失败,序列号:[{0}],设备号:[{1}],Success:[{2}],Msg:[{3}],时间:[{4}]", lot.LotNo, lot.DeviceNo, lot.Success, lot.Msg, lot.CreateTime));
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                WriteListBoxToFile(ex.Message);
                log.WriteExceptionLog(ex.Message);
            }
            waitHandler.Set();
        }
        private void btnDispatch_Click(object sender, EventArgs e)
        {
            btnDispatch.Enabled = false;
            if (txtDeviceName.Text.Length < 10)
            {
                MessageBox.Show("设备号名称长度不能小于10个字符");
                btnDispatch.Enabled = true;
                lstbar.Items.Clear();
                return;
            }

            if (lstbar.Items.Count > 0)
            {
                if (bgWorker.IsBusy != true)
                {
                    waitHandler = new AutoResetEvent(false);
                    bgWorker.RunWorkerAsync(lstbar.Items.Count);
                }
            }
            else
            {
                MessageBox.Show("列表框内至少存在1个条码才可以过站");
            }
            btnDispatch.Enabled = true;
        }
        private void BgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            for (int i = 0; i < (int)e.Argument; i++)
            {
                if (worker.CancellationPending == true)
                {
                    e.Cancel = true;
                    break;
                }
                else
                {
                    if (tSet.ScanMode == "S")
                    {
                        System.Threading.Thread.Sleep(10);
                    }
                    else
                    {
                        System.Threading.Thread.Sleep(tSet.IntervalTime);
                    }
                    worker.ReportProgress(i);
                    waitHandler.WaitOne();
                }
            }
        }

这个方法也不是我想出来的,参考了下面的大神

使用BackgroundWorker时,出现ProgressChanged延迟的现象,请帮分析下原因

原文地址:https://www.cnblogs.com/masonlu/p/11470965.html