Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
CODE PROJECT For Those Who Code
  • Home
  • Articles
  • FAQ
Community
  1. Home
  2. General Programming
  3. C#
  4. C# Stopwatch - DateTime And Timer Tick - Is there a better way to run the Stopwatch

C# Stopwatch - DateTime And Timer Tick - Is there a better way to run the Stopwatch

Scheduled Pinned Locked Moved C#
csharplinqgraphics
5 Posts 5 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • U Offline
    U Offline
    User 12723023
    wrote on last edited by
    #1

    Is there a better way to run the Stop Watch: Form1.cs

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.Diagnostics;

    namespace StopWatch
    {
    public partial class Form1 : Form
    {
    public Form1()
    {
    InitializeComponent();
    }

        // new instance of Stop Watch
        Stopwatch StopWatch = new Stopwatch();
        
        private void lblClock\_Click(object sender, EventArgs e)
        {
    
        }
    
        private void btnStart\_Click(object sender, EventArgs e)
        {
            // Button Start Checking if already started
            if (timer1.Enabled)
            {
                MessageBox.Show("Sorry you have already started the Timer");
            }
    
            else
                 timer1.Start();
                 this.StopWatch.Start();
        }
    
        private void btnStop\_Click(object sender, EventArgs e)
        {
            // Button Stop Checking if already Stopped
            if (timer1.Enabled)
            {
                timer1.Stop();
                StopWatch.Stop();
            }
            else
                MessageBox.Show("Timer Already Stopped");
        }
    
        private void btnPause\_Click(object sender, EventArgs e)
        {
            // button reset
            StopWatch.Reset();
            lblClock.Text = "00 HR :00 MIN :00 SEC ";
        }
    
        private void timer1\_Tick(object sender, EventArgs e)
        {
    
            // Timer by hr min sec
             TimeSpan elapsed = this.StopWatch.Elapsed;
             lblClock.Text = string.Format("{0:00} HR :{1:00} MIN: {2:00} SEC", Math.Floor(elapsed.TotalHours), elapsed.Minutes, elapsed.Seconds);
    
        }
    }
    

    }

    Class1.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Diagnostics;

    namespace StopWatch.BL
    {
    public class Time
    {
    Stopwatch stopwatch = new Stopwatch();

        public TimeSpan Elapsed // class elapsed
        {
            get { return stopwatch.Elapsed; }
        }
    
        public bool IsRunning // class is running
        {
            get { return stopwatch.IsRunning; }
        }
    
    
        public void Start() // start stop watch
    
    M OriginalGriffO B O 4 Replies Last reply
    0
    • U User 12723023

      Is there a better way to run the Stop Watch: Form1.cs

      using System;
      using System.Collections.Generic;
      using System.ComponentModel;
      using System.Data;
      using System.Drawing;
      using System.Linq;
      using System.Text;
      using System.Threading.Tasks;
      using System.Windows.Forms;
      using System.Diagnostics;

      namespace StopWatch
      {
      public partial class Form1 : Form
      {
      public Form1()
      {
      InitializeComponent();
      }

          // new instance of Stop Watch
          Stopwatch StopWatch = new Stopwatch();
          
          private void lblClock\_Click(object sender, EventArgs e)
          {
      
          }
      
          private void btnStart\_Click(object sender, EventArgs e)
          {
              // Button Start Checking if already started
              if (timer1.Enabled)
              {
                  MessageBox.Show("Sorry you have already started the Timer");
              }
      
              else
                   timer1.Start();
                   this.StopWatch.Start();
          }
      
          private void btnStop\_Click(object sender, EventArgs e)
          {
              // Button Stop Checking if already Stopped
              if (timer1.Enabled)
              {
                  timer1.Stop();
                  StopWatch.Stop();
              }
              else
                  MessageBox.Show("Timer Already Stopped");
          }
      
          private void btnPause\_Click(object sender, EventArgs e)
          {
              // button reset
              StopWatch.Reset();
              lblClock.Text = "00 HR :00 MIN :00 SEC ";
          }
      
          private void timer1\_Tick(object sender, EventArgs e)
          {
      
              // Timer by hr min sec
               TimeSpan elapsed = this.StopWatch.Elapsed;
               lblClock.Text = string.Format("{0:00} HR :{1:00} MIN: {2:00} SEC", Math.Floor(elapsed.TotalHours), elapsed.Minutes, elapsed.Seconds);
      
          }
      }
      

      }

      Class1.cs

      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Text;
      using System.Threading.Tasks;
      using System.Diagnostics;

      namespace StopWatch.BL
      {
      public class Time
      {
      Stopwatch stopwatch = new Stopwatch();

          public TimeSpan Elapsed // class elapsed
          {
              get { return stopwatch.Elapsed; }
          }
      
          public bool IsRunning // class is running
          {
              get { return stopwatch.IsRunning; }
          }
      
      
          public void Start() // start stop watch
      
      M Offline
      M Offline
      Midi_Mick
      wrote on last edited by
      #2

      This very much depends on the application and level of accuracy required. Your sample provides the simplest solution, but it lacks a degree of accuracy, as everything is processed on the UI thread. Using this system, a timer event is actually placed on the message queue when it is signalled, and thus needs to wait its turn to be processed. This can cause a delay small in the processing of the tick, which over time, may accumulate. To go to the next level of accuracy, you need to look at a System.Threading.Timer[^]. These fire events off in another thread, so there is no queue delays. It does, however, take a bit of effort to marshal the results back to the UI thread to update your controls. The most accurate timer is the High Resolution Timer used in the Stopwatch Class[^]. This does not fire its own events at all, so you need to monitor its values in a separate thread, fire the periodic events in another thread, and then marshal all the results back to the UI for display. All three options are good fun!

      Cheers, Mick ------------------------------------------------ It doesn't matter how often or hard you fall on your arse, eventually you'll roll over and land on your feet.

      1 Reply Last reply
      0
      • U User 12723023

        Is there a better way to run the Stop Watch: Form1.cs

        using System;
        using System.Collections.Generic;
        using System.ComponentModel;
        using System.Data;
        using System.Drawing;
        using System.Linq;
        using System.Text;
        using System.Threading.Tasks;
        using System.Windows.Forms;
        using System.Diagnostics;

        namespace StopWatch
        {
        public partial class Form1 : Form
        {
        public Form1()
        {
        InitializeComponent();
        }

            // new instance of Stop Watch
            Stopwatch StopWatch = new Stopwatch();
            
            private void lblClock\_Click(object sender, EventArgs e)
            {
        
            }
        
            private void btnStart\_Click(object sender, EventArgs e)
            {
                // Button Start Checking if already started
                if (timer1.Enabled)
                {
                    MessageBox.Show("Sorry you have already started the Timer");
                }
        
                else
                     timer1.Start();
                     this.StopWatch.Start();
            }
        
            private void btnStop\_Click(object sender, EventArgs e)
            {
                // Button Stop Checking if already Stopped
                if (timer1.Enabled)
                {
                    timer1.Stop();
                    StopWatch.Stop();
                }
                else
                    MessageBox.Show("Timer Already Stopped");
            }
        
            private void btnPause\_Click(object sender, EventArgs e)
            {
                // button reset
                StopWatch.Reset();
                lblClock.Text = "00 HR :00 MIN :00 SEC ";
            }
        
            private void timer1\_Tick(object sender, EventArgs e)
            {
        
                // Timer by hr min sec
                 TimeSpan elapsed = this.StopWatch.Elapsed;
                 lblClock.Text = string.Format("{0:00} HR :{1:00} MIN: {2:00} SEC", Math.Floor(elapsed.TotalHours), elapsed.Minutes, elapsed.Seconds);
        
            }
        }
        

        }

        Class1.cs

        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Text;
        using System.Threading.Tasks;
        using System.Diagnostics;

        namespace StopWatch.BL
        {
        public class Time
        {
        Stopwatch stopwatch = new Stopwatch();

            public TimeSpan Elapsed // class elapsed
            {
                get { return stopwatch.Elapsed; }
            }
        
            public bool IsRunning // class is running
            {
                get { return stopwatch.IsRunning; }
            }
        
        
            public void Start() // start stop watch
        
        OriginalGriffO Offline
        OriginalGriffO Offline
        OriginalGriff
        wrote on last edited by
        #3

        Don't use a StopWatch - just get the current DateTime.Now when you start the timer, and again when you stop (or lap check) it. The Timespan difference will give you all the information you need.

        Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...

        "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
        "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

        1 Reply Last reply
        0
        • U User 12723023

          Is there a better way to run the Stop Watch: Form1.cs

          using System;
          using System.Collections.Generic;
          using System.ComponentModel;
          using System.Data;
          using System.Drawing;
          using System.Linq;
          using System.Text;
          using System.Threading.Tasks;
          using System.Windows.Forms;
          using System.Diagnostics;

          namespace StopWatch
          {
          public partial class Form1 : Form
          {
          public Form1()
          {
          InitializeComponent();
          }

              // new instance of Stop Watch
              Stopwatch StopWatch = new Stopwatch();
              
              private void lblClock\_Click(object sender, EventArgs e)
              {
          
              }
          
              private void btnStart\_Click(object sender, EventArgs e)
              {
                  // Button Start Checking if already started
                  if (timer1.Enabled)
                  {
                      MessageBox.Show("Sorry you have already started the Timer");
                  }
          
                  else
                       timer1.Start();
                       this.StopWatch.Start();
              }
          
              private void btnStop\_Click(object sender, EventArgs e)
              {
                  // Button Stop Checking if already Stopped
                  if (timer1.Enabled)
                  {
                      timer1.Stop();
                      StopWatch.Stop();
                  }
                  else
                      MessageBox.Show("Timer Already Stopped");
              }
          
              private void btnPause\_Click(object sender, EventArgs e)
              {
                  // button reset
                  StopWatch.Reset();
                  lblClock.Text = "00 HR :00 MIN :00 SEC ";
              }
          
              private void timer1\_Tick(object sender, EventArgs e)
              {
          
                  // Timer by hr min sec
                   TimeSpan elapsed = this.StopWatch.Elapsed;
                   lblClock.Text = string.Format("{0:00} HR :{1:00} MIN: {2:00} SEC", Math.Floor(elapsed.TotalHours), elapsed.Minutes, elapsed.Seconds);
          
              }
          }
          

          }

          Class1.cs

          using System;
          using System.Collections.Generic;
          using System.Linq;
          using System.Text;
          using System.Threading.Tasks;
          using System.Diagnostics;

          namespace StopWatch.BL
          {
          public class Time
          {
          Stopwatch stopwatch = new Stopwatch();

              public TimeSpan Elapsed // class elapsed
              {
                  get { return stopwatch.Elapsed; }
              }
          
              public bool IsRunning // class is running
              {
                  get { return stopwatch.IsRunning; }
              }
          
          
              public void Start() // start stop watch
          
          B Offline
          B Offline
          Bernhard Hiller
          wrote on last edited by
          #4

          Ehm, that looks like a hidden bug:

          if (timer1.Enabled)
          {
          MessageBox.Show("Sorry you have already started the Timer");
          }

          else
          timer1.Start();
          this.StopWatch.Start();

          Did you really mean that? Or rather

                  if (timer1.Enabled)
                  {
                      MessageBox.Show("Sorry you have already started the Timer");
                  }
                  else
                  {
                       timer1.Start();
                       this.StopWatch.Start();
                  }
          

          Anyway, I recommend to always use {} with if and else - also with one-liners.

          1 Reply Last reply
          0
          • U User 12723023

            Is there a better way to run the Stop Watch: Form1.cs

            using System;
            using System.Collections.Generic;
            using System.ComponentModel;
            using System.Data;
            using System.Drawing;
            using System.Linq;
            using System.Text;
            using System.Threading.Tasks;
            using System.Windows.Forms;
            using System.Diagnostics;

            namespace StopWatch
            {
            public partial class Form1 : Form
            {
            public Form1()
            {
            InitializeComponent();
            }

                // new instance of Stop Watch
                Stopwatch StopWatch = new Stopwatch();
                
                private void lblClock\_Click(object sender, EventArgs e)
                {
            
                }
            
                private void btnStart\_Click(object sender, EventArgs e)
                {
                    // Button Start Checking if already started
                    if (timer1.Enabled)
                    {
                        MessageBox.Show("Sorry you have already started the Timer");
                    }
            
                    else
                         timer1.Start();
                         this.StopWatch.Start();
                }
            
                private void btnStop\_Click(object sender, EventArgs e)
                {
                    // Button Stop Checking if already Stopped
                    if (timer1.Enabled)
                    {
                        timer1.Stop();
                        StopWatch.Stop();
                    }
                    else
                        MessageBox.Show("Timer Already Stopped");
                }
            
                private void btnPause\_Click(object sender, EventArgs e)
                {
                    // button reset
                    StopWatch.Reset();
                    lblClock.Text = "00 HR :00 MIN :00 SEC ";
                }
            
                private void timer1\_Tick(object sender, EventArgs e)
                {
            
                    // Timer by hr min sec
                     TimeSpan elapsed = this.StopWatch.Elapsed;
                     lblClock.Text = string.Format("{0:00} HR :{1:00} MIN: {2:00} SEC", Math.Floor(elapsed.TotalHours), elapsed.Minutes, elapsed.Seconds);
            
                }
            }
            

            }

            Class1.cs

            using System;
            using System.Collections.Generic;
            using System.Linq;
            using System.Text;
            using System.Threading.Tasks;
            using System.Diagnostics;

            namespace StopWatch.BL
            {
            public class Time
            {
            Stopwatch stopwatch = new Stopwatch();

                public TimeSpan Elapsed // class elapsed
                {
                    get { return stopwatch.Elapsed; }
                }
            
                public bool IsRunning // class is running
                {
                    get { return stopwatch.IsRunning; }
                }
            
            
                public void Start() // start stop watch
            
            O Offline
            O Offline
            omeecode
            wrote on last edited by
            #5

            There is no problem with your code if that can solve your problem. From design point of view it looks great. As one answer above mentioned that you can use many other types of solution to accomplish timing and scheduling task. That also depend upon your needs. If you need a precise timer such as with 1ms accuracy (Stopwatch can very up-to 20-100 ms) then you should use multimedia timers.

            Umair www.objectorienteddesign.org (Interested in C#, .Net, Interfacing, Device Drivers, GIS, WCF, Asp.net, Ajax, Architecture and Design Patterns)

            1 Reply Last reply
            0
            Reply
            • Reply as topic
            Log in to reply
            • Oldest to Newest
            • Newest to Oldest
            • Most Votes


            • Login

            • Don't have an account? Register

            • Login or register to search.
            • First post
              Last post
            0
            • Categories
            • Recent
            • Tags
            • Popular
            • World
            • Users
            • Groups