0

I am wondering what is the best way to achieve this in Windows Forms - what I need is a window showing time elapsed (1 sec 2 secs etc) up to 90 seconds while code is being executed. I have a timer right now implemented as follows but I think I also need a stopwatch there as well since the Timer blocks the main thread.

 static System.Timers.Timer pXRFTimer = new System.Timers.Timer();       
  static int _pXRFTimerCounter = 0;


   private void ScanpXRF()
        {
            _pXRFTimerCounter = 0;
            pXRFTimer.Enabled = true;
            pXRFTimer.Interval = 1000;
            pXRFTimer.Elapsed += new ElapsedEventHandler(pXRFTimer_Tick);
            pXRFTimer.Start();

            //START action to be measured here!
            DoSomethingToBeMeasured();

        }

        private static void pXRFTimer_Tick(Object sender, EventArgs e)
        {
            _pXRFTimerCounter++;

            if (_pXRFTimerCounter >= 90)
            {
                pXRFTimer.Stop();             
            }
            else
            {
                //show time elapsed
            }
        }
sarsnake
  • 26,667
  • 58
  • 180
  • 286
  • Use a `System.Windows.Forms.Timer` (you can drag on onto the form from the toolbox) and a `private Stopwatch` object. – Rufus L Oct 18 '19 at 22:36
  • @Rufus it did not work, did not fire. So I replaced it with this one – sarsnake Oct 18 '19 at 22:38
  • 1
    @RufusL From [Timer firing every second and updating GUI (C# Windows Forms)](https://stackoverflow.com/a/58440427/719186), he commented "One thing I could think of after reading the documentation is that my app is not single threaded." – LarsTech Oct 18 '19 at 22:40
  • It sounds like you want a timer to update the UI (might have to do something like https://stackoverflow.com/questions/661561/how-do-i-update-the-gui-from-another-thread) and a stopwatch to measure the time. Have you tried the `System.Threading.Timer` class? – Rufus L Oct 18 '19 at 22:58
  • No I haven't, that's why I am asking. thank you! So where does the timer start? – sarsnake Oct 18 '19 at 23:00
  • 1
    Not sure if it will help, but hopefully! – Rufus L Oct 18 '19 at 23:01

1 Answers1

0

I'm not sure about mechanics of your app, but time elapsed can be calculated with something like this

DateTime startUtc;

private void ScanpXRF()
{
  startUtc = DateTime.NowUtc;
  (...)

  //START action to be measured here!
}

private static void pXRFTimer_Tick(Object sender, EventArgs e)
{
  var elapsed = DateTime.NowUtc - startUtc;
  var elapsedSeconds = elapsed.TotalSeconds; // double so you may want to round.
}
tymtam
  • 31,798
  • 8
  • 86
  • 126
  • Thank you! How can I update the UI with this answer? As I noted in the question - I need the elapsed time displayed every second – sarsnake Oct 21 '19 at 15:52