C#计时利器:Stopwatch的使用

      本文演示C#计时器:Stopwatch的使用。

     页面代码:


    
        
后台代码:

using System;
using System.Windows;
using System.Timers;
using System.Diagnostics;

namespace TestStopwatch
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        private Timer _timer;
        private Stopwatch _stopWath;
        public MainWindow()
        {
            InitializeComponent();
            _timer = new Timer(500);
            _timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
            _timer.Start();
            _stopWath = new Stopwatch();

        }

        void _timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            //查看计时器的时间
            this.Dispatcher.Invoke((Action)delegate
            {
                this.textBlock1.Text = _stopWath.Elapsed.Minutes.ToString() + ":" + _stopWath.Elapsed.Seconds.ToString() + ":" + _stopWath.Elapsed.Milliseconds.ToString();

            });
        }


        private void btn_Start_Click(object sender, RoutedEventArgs e)
        {
            _stopWath.Start();
        }

        private void btn_Stop_Click(object sender, RoutedEventArgs e)
        {
            _stopWath.Stop();
        }

        private void btn_Restart_Click(object sender, RoutedEventArgs e)
        {
            _stopWath.Restart();
        }

        private void btn_Reset_Click(object sender, RoutedEventArgs e)
        {
            _stopWath.Reset();
        }
    }
}

       经过测试发现Stopwatch还是挺好用的,其中的Restart方法等于Reset+Start。


源代码:http://download.csdn.net/detail/jiangzhanchang/4520665

转载请随便。


你可能感兴趣的:(C#,Visual,Studio,2010,WPF)