Search code examples
c#winformsstopwatch

How to run stopwatch infinitely


I am working on a windows forms application and I want to calculate elapsed time infinitely until I tell it to stop by the use of a boolean flag in my code that will control the execution flow.

The only sample code I have is the one provided by MSDN. But now, the problem is that it calculates the time for 10 seconds only which makes sense seeing that the thread is being put to sleep for only 10 seconds and then afterwards the stopwatch is stopped.

I strongly believe the use of Thread.Sleep(10000) is the major hindrance here. Please find below the MSDN code used in reference here:

 private string CalculateDowntime()
{ 
    Stopwatch stopWatch = new Stopwatch();
        stopWatch.Start();
        Thread.Sleep(10000);
        stopWatch.Stop();
        // Get the elapsed time as a TimeSpan value.
        TimeSpan ts = stopWatch.Elapsed;

        // Format and display the TimeSpan value.
        string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
            ts.Hours, ts.Minutes, ts.Seconds,
            ts.Milliseconds / 10);
        return elapsedTime);;
}

Any suggestions on how I can achieve this?

Update: To further clarify, upon button click, I want to calculate time (whether its using a stopwatch or timer, I really don't care) infinitely until I tell it to stop. That's all!


Solution

  • Make the stopwatch variable a property on your class.

    Add methods to start / stop the stop watch.

    You can also get the elapsed time after stopping.

    Here is example code in a wpf program with two buttons:

    When you click the start button the timer will start, when you click the stop button the timer will stop and show a message box with the elapsed milliseconds.

    using System.Diagnostics;
    using System.Windows;
    
    namespace StopWatch
    {
       /// <summary>
       /// Interaction logic for MainWindow.xaml
       /// </summary>
       public partial class MainWindow : Window
       {
          public MainWindow()
          {
             InitializeComponent();
          }
    
          public Stopwatch MyStopWatch = new Stopwatch();
    
          private void Start_Button_Click( object sender, RoutedEventArgs e )
          {
             MyStopWatch.Start();
          }
    
          private void Stop_Button_Click( object sender, RoutedEventArgs e )
          {
             MyStopWatch.Stop();
             MessageBox.Show( MyStopWatch.ElapsedMilliseconds.ToString() );
          }
       }
    }