0

I have a problem with timerTick() because it executes every 0.5 seconds, for me it's ok because he checks every 0.5 seconds for connectetCard(), now if so he should assign it The 5 seconds that I in _bw.DoWork assigned to run, how can I set timerTick() to fire again, but only when the process in backgroundWorker is completed.

This is my code:

public FormMenu()
        {
            InitializeComponent();

            SelectDevice();
            establishContext();
            timerBatch.Start();
            _bw = new BackgroundWorker
            {
                WorkerReportsProgress = true,
                WorkerSupportsCancellation = true
            };

        }   

private void timerBatch_Tick(object sender, EventArgs e)
        {
            if (connectCard())
            {
                cardUID = getcardUID();
                if (cardUID != "Error")
                {
                    using (DBEntities db = new DBEntities())
                    {
                        try
                        {
                            personData = db.Persons.Where(x => x.BATCH_ID == cardUID).FirstOrDefault();
                            if (maDaten == null)
                            {
                                labelInfo.Text = "Batch invalid.";
                                return;
                            }
                            else
                            {
                                person = db.Person.Where(x => x.LPE_ID == personData.MA_ID).FirstOrDefault();
                                _bw.DoWork += _bw_DoWork;
                                _bw.ProgressChanged += bw_ProgressChanged;
                                _bw.RunWorkerCompleted += bw_RunWorkerCompleted;
                                _bw.RunWorkerAsync();
                            }                         
                        }
                        catch (Exception es)
                        {
                            MessageBox.Show(es.Message);
                        }

                    };
                }
            }
        }

  private void _bw_DoWork(object sender, DoWorkEventArgs e)
        {
            for (int i = 5; i >= 0; i -= 1)
            {
                if (_bw.CancellationPending) { 
                    e.Cancel = true; return; 
                }
                if (i == 0)
                {
                    e.Cancel = true; return;
                }
                _bw.ReportProgress(i);
                Thread.Sleep(1000);
            }            
        }

   private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            labelInfo.Text = "Hello " + person.FirstName + " " + person.LastName + " " + e.ProgressPercentage.ToString();

        }

  private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            labelInfo.Text = labelInfo.Text.Trim();
        }
6
  • Consider using Monitor to effectively lock when the process is in flight.
    – mjwills
    Apr 15, 2020 at 8:18
  • @mjwills ok, interesting recommendation, could any example please?
    – merci
    Apr 15, 2020 at 8:20
  • BackgroundWorker has a RunWorkerCompleted event, which fires when the work is done. You could use this to set a flag that you can check against in your timer callback. Apr 15, 2020 at 8:29
  • @500-InternalServerError thanks for the reply, could you please give me a little help on how to do this?
    – merci
    Apr 15, 2020 at 8:43
  • Sure. I didn't notice earlier that you already have an event handler for RunWorkerCompleted. Since you do it should just be a matter of introducing a bool backgroundWorkerRunning;, set that to true right before the RunWorkerAsync call, then test for it at the top of the timer call back, with if (backgroundWorkerRunning) return;. The completion callback should set the flag to false, of course. Apr 15, 2020 at 8:59

1 Answer 1

0

Try something like this:

public FormMenu()
        {
            InitializeComponent();

            SelectDevice();
            establishContext();
            timerBatch.Start();
            _bw = new BackgroundWorker
            {
                WorkerReportsProgress = true,
                WorkerSupportsCancellation = true
            };

        }   

//CHANGE:
bool backgroundworkerRunning = false;

private void timerBatch_Tick(object sender, EventArgs e)
        {
            //CHANGE:
            if (backgroundworkerRunning)
              return;

            if (connectCard())
            {
                cardUID = getcardUID();
                if (cardUID != "Error")
                {
                    using (DBEntities db = new DBEntities())
                    {
                        try
                        {
                            personData = db.Persons.Where(x => x.BATCH_ID == cardUID).FirstOrDefault();
                            if (maDaten == null)
                            {
                                labelInfo.Text = "Batch invalid.";
                                return;
                            }
                            else
                            {
                                person = db.Person.Where(x => x.LPE_ID == personData.MA_ID).FirstOrDefault();
                                _bw.DoWork += _bw_DoWork;
                                _bw.ProgressChanged += bw_ProgressChanged;
                                _bw.RunWorkerCompleted += bw_RunWorkerCompleted;
                                //CHANGE:
                                backgroundworkerRunning = true; 
                                _bw.RunWorkerAsync();
                            }                         
                        }
                        catch (Exception es)
                        {
                            MessageBox.Show(es.Message);
                        }

                    };
                }
            }
        }

  private void _bw_DoWork(object sender, DoWorkEventArgs e)
        {
            for (int i = 5; i >= 0; i -= 1)
            {
                if (_bw.CancellationPending) { 
                    e.Cancel = true; return; 
                }
                if (i == 0)
                {
                    e.Cancel = true; return;
                }
                _bw.ReportProgress(i);
                Thread.Sleep(1000);
            }            
        }

   private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            labelInfo.Text = "Hello " + person.FirstName + " " + person.LastName + " " + e.ProgressPercentage.ToString();

        }

  private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //CHANGE:
            backgroundworkerRunning = false; 
            labelInfo.Text = labelInfo.Text.Trim();
        }
2
  • I changed the code, it works better, it's not only clear to me why he does 5 times countdown 5,4,3,2,1 (repeats all the time), after the first countdown, I should display labelinfo.trim.text.
    – merci
    Apr 15, 2020 at 9:24
  • That's a different issue. I can't run your code, obviously. You'll have to investigate and make appropriate changes yourself. Post another question if you get completely stuck. Apr 15, 2020 at 9:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.