StopWatch Or Timer

断了今生、忘了曾经 提交于 2019-12-12 03:07:34

问题


The timer in my opinion is not very accurate when it displays time from its _Tick() Method. I am wanting to show elapsed time in minutes/seconds show the length of time a procedure takes to complete. I have used this with the Timer but have discovered it's calculations are incorrect. Which is why I wanted to ask would a StopWatch be better to show more accurately or is their a separate control that I should be using altogether?

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

回答1:


Here's one way to accomplish this with a stop watch, which should be very accurate:

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



回答2:


System.Diagnostics.StopWatch is the typical method for tracking this sort of thing. If you are using VS and are just trying to do performance checks, you could also profile the code while will give you a good idea of how much time is spent in each method.



来源:https://stackoverflow.com/questions/29498525/stopwatch-or-timer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!