秒表或计时器

时间:2015-04-07 18:24:13

标签: c# winforms timer stopwatch

我认为计时器从_Tick()方法显示时间时不是很准确。我希望以分钟/秒显示经过的时间,显示程序完成所需的时间长度。我在计时器中使用了它,但发现它的计算结果不正确。这就是为什么我想问一个StopWatch会更好地展示更准确,还是他们应该完全使用它们的单独控件呢?

private int timepassed = 0;
private void buttonFourteen_Click(object sender, DragEventArgs e)
{
  timer2.Start();
  var backgroundWorker = new BackgroundWorker();
  backgroundWorker.DoWork += (s, e) =>
  {
    //Lengthy Procedure Goes Here
  };
  backgroundWorker.RunWorkerCompleted += (s, e) =>
  {
    timer2.Stop();
  };
  backgroundWorker.RunWorkerAsync();
}
private void timer2_Tick(object sender, EventArgs e)
{
  timepassed++;
  timedisplay.Text = timepassed.ToString();
}

2 个答案:

答案 0 :(得分:2)

System.Diagnostics.StopWatch是跟踪此类事情的典型方法。如果您正在使用VS并且只是尝试进行性能检查,您还可以对代码进行概要分析,同时让您了解每种方法花费的时间。

答案 1 :(得分:2)

这是使用秒表实现此目标的一种方法,这应该是非常准确的:

private readonly Stopwatch sw = new Stopwatch();
private readonly System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();

public Form1()
{
    InitializeComponent();
    timer.Tick += timer2_Tick;
}

private void buttonFourteen_Click(object sender, EventArgs e)
{
    sw.Restart();
    timer.Start();
    var backgroundWorker = new BackgroundWorker();

    // Simulating a 10-second process for testing
    backgroundWorker.DoWork += (s, ea) => Thread.Sleep(TimeSpan.FromSeconds(10));

    backgroundWorker.RunWorkerCompleted += (s, ea) => timer.Stop();
    backgroundWorker.RunWorkerAsync();
}

private void timer2_Tick(object sender, EventArgs e)
{
    timedisplay.Text = sw.Elapsed.ToString("g");

    // Or use a custom time format (you can specify precision as well as
    // delimiters between days, hours, minutes, seconds, and milliseconds):
    // timedisplay.Text = sw.Elapsed.ToString(@"dd\.hh\:mm\:ss\.ff");
}