后台工作人员第二次运行时,运行完成的工作人员在执行工作中执行

时间:2018-03-13 21:12:05

标签: c# wpf multithreading

我有后台工作者,我在一个线程中得到一些回调,我正在更新UI和进度条随着状态的变化。目前有3个州1)Cartridgr抽屉关闭2)处理3)处理。

第一次应用程序启动时一切正常。 “已处理”状态后,“运行工作者已完成”将触发,我将通过事件启动另一个成功窗口。

但是,当我重新运行工作流程而不关闭应用程序时,当工作人员仍然说处理时,我得到了成功窗口。为什么这也是我更新的剩余时间表现不正确。请帮忙。 (请参阅DoWork事件线程,我想这就是问题)。

 //This method is a RelayCommand thats called on some button click
    private void StartCurrentRun(bool obj)
            {
                this.worker = new BackgroundWorker();
                this.worker.WorkerReportsProgress = true;
                this.worker.WorkerSupportsCancellation = true;
                StartTimer();
                PropertyCallBackChangedInstance.PropertyChanged -= PropertyCallBackChangedInstance_PropertyChanged;
                WhenCancelledBlurVolumesGrid = false;
                this.worker.DoWork += this.DoWork;
                this.worker.ProgressChanged += this.ProgressChanged;
                this.worker.RunWorkerCompleted += Worker_RunWorkerCompleted;
                IsLiveProgress = true;
                this.worker.RunWorkerAsync();
            }

    private void DoWork(object sender, DoWorkEventArgs e)
            {


                    int OriginalTimeRemaining = SelectedVolumeEstimatedTime();
                    int TotalPrecentagebasedOnNumberOfStates = 50;
                    int PercentProgress = 100 / TotalPrecentagebasedOnNumberOfStates;
                    CurrentCartridgeStatus status = CurrentCartridgeStatus.NotProcessed;
                    var instance = ConnectToInstrument.InstrumentConnectionInstance;
                    instance.InitalizeRun();

                    Thread th = new Thread(() =>
                    {
                        PropertyCallBackChangedInstance.PropertyChanged += PropertyCallBackChangedInstance_PropertyChanged;
                    });

                    th.Start();
                    Thread th2 = new Thread(() =>
                      {
                          while (PropertyCallBackChangedInstance.CurrentCartridgeStatusChanged != CurrentCartridgeStatus.Processed)
                          {
                              lock (_objectForThread2)
                              {
                                  if (OriginalTimeRemaining > 0)
                                  {
                                      OriginalTimeRemaining -= 2;
                                  }
                                  var time = TimeSpan.FromSeconds(OriginalTimeRemaining);
                                  EstimatedTimeRemaining = string.Format("{0:00}:{1:00}:{2:00}",
                            time.Hours,
                            time.Minutes,
                            time.Seconds);
                                  OnPropertyChanged("EstimatedTimeRemaining");
                              }
                              Thread.Sleep(2000);
                          }
                      });
                    th2.Start();
                    int counter = 0;
                    for (int i = 0; i < PercentProgress; i++)
                    {
                        //Keep checking to see if the Run is cancelled
                        if (WhenCancelledBlurVolumesGrid) //That means the run is cancelled
                        {
                            if (worker.CancellationPending)
                            {
                                e.Cancel = true;
                                worker.CancelAsync();
                            }
                        }
                        for (int j = counter; j <= TotalPrecentagebasedOnNumberOfStates; j++)
                        {
                            worker.ReportProgress(Math.Min(j, 100));
                            if (status != CurrentCartridgeStatus.Processed)
                            {
                                Thread.Sleep(55);
                            }
                        }
                        counter = 50;
                        TotalPrecentagebasedOnNumberOfStates += 50;
                    }
                    th.Join();
                    th2.Join();
                }



            private void PropertyCallBackChangedInstance_PropertyChanged(object sender, PropertyChangedEventArgs e)
            {
                if (e.PropertyName == "CurrentCartridgeStatusChanged")
                {
                    var value = sender as InstrumentCallBackProperties;
                    CurrentStatus = EnumExtensions.GetDescription(value.CurrentCartridgeStatusChanged);
                }
            }

            private void ProgressChanged(object sender, ProgressChangedEventArgs e)
            {
                this.ProgressValue = e.ProgressPercentage;
            }

            private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
            {
                EstimatedTimeRemaining = "00:00:00";

                stopWatch.Stop();
                timer.Stop();

                Messenger.Default.Send(new NotificationMessage("RunComplete"));
                if (e.Cancelled)
                {
                    SelectedVolume = string.Empty;
                }


                else
                {
                    IsLiveProgress = false;

                    if (IsRunSuccessfullyComplete != null && !WhenCancelledBlurVolumesGrid) //This indicates that Success will only open when the run is complete
                    {

                        IsRunSuccessfullyComplete(NoErrors);//This event opens the success window from a different page
                    }

                WhenCancelledBlurVolumesGrid = true;
            }

    //I have some Dispose method that i am trying to do after the first run.
    public void Dispose()
            {
                if (this.worker != null)
                {
                    this.ProgressValue = 0;
                    this.worker.CancelAsync();
                    this.worker.Dispose();
                    this.worker = null;
                    timer = null;
                    stopWatch = null;
                    TimeElapsed = string.Empty;
                }
            }

0 个答案:

没有答案