秒表或计时器 [英] StopWatch Or Timer
本文介绍了秒表或计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我看来,当它从 _Tick()
方法显示时间时,计时器不是很准确.我想以分钟/秒为单位显示经过的时间,以显示程序完成所需的时间长度.我已经将它与 Timer 一起使用,但发现它的计算不正确.这就是为什么我想问秒表是更好地显示更准确还是它们是我应该完全使用的单独控件?
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();
}
推荐答案
这里有一种用秒表完成此任务的方法,应该非常准确:
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");
}
这篇关于秒表或计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文