【问题标题】:StopWatch Or Timer秒表或计时器
【发布时间】:2015-06-12 11:01:25
【问题描述】:

在我看来,计时器从其_Tick() 方法显示时间时并不是很准确。我想以分钟/秒为单位显示经过的时间,显示完成过程所需的时间长度。我已经将它与 Timer 一起使用,但发现它的计算不正确。这就是为什么我想问一下秒表会更好地显示更准确,还是我应该完全使用它们的单独控件?

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();
}

【问题讨论】:

  • show the length of time a procedure takes to complete 你想要一个秒表。 Timer 更适合按设定的时间间隔执行操作。
  • 使用合适的工具来做你想做的事。 Stopwatch 用于测量经过的时间。 Timer 用于调度。至少您没有使用DateTime 进行测量,因为这也不适用于精确的间隔测量。
  • 我会使用计时器并保存开始时间,以通过Now - Start 计算时差。测试性能时需要秒表来确保准确性,而不是显示最多 2 个小数点精度的计时器。

标签: c# winforms timer stopwatch


【解决方案1】:

这是用秒表完成此任务的一种方法,它应该非常准确:

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");
}

【讨论】:

  • 我得到一个编译错误,'Timer' is ambiguous between 'System.Windows.Forms.Timer' and 'System.Threading.Timer'
  • 我使用了 Windows.Forms...我已使用显式类型更新示例。
【解决方案2】:

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

【讨论】:

  • 是的,我正在使用 VS2010 -- 我将如何分析代码?
  • 基本上你启动你的应用程序,让它接近将影响代码的状态,然后在 VS 中转到分析、分析器、附加/分离。在此处查看 VS Profiler 上的初学者参考资料:msdn.microsoft.com/en-us/library/ms182372.aspx
猜你喜欢
  • 2015-10-20
  • 2012-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-15
  • 1970-01-01
  • 2012-03-02
  • 2013-01-18
相关资源
最近更新 更多