我想知道在Windows窗体中实现此目标的最佳方法是什么-我需要一个窗口,该窗口显示执行代码时经过的时间(1秒2秒等),最长90秒。我现在有一个实现如下的计时器,但是我认为我也需要在那里使用秒表,因为计时器会阻塞主线程。
static System.Timers.Timer pXRFTimer = new System.Timers.Timer();
static int _pXRFTimerCounter = 0;
private void ScanpXRF()
{
_pXRFTimerCounter = 0;
pXRFTimer.Enabled = true;
pXRFTimer.Interval = 1000;
pXRFTimer.Elapsed += new ElapsedEventHandler(pXRFTimer_Tick);
pXRFTimer.Start();
//START action to be measured here!
DoSomethingToBeMeasured();
}
private static void pXRFTimer_Tick(Object sender, EventArgs e)
{
_pXRFTimerCounter++;
if (_pXRFTimerCounter >= 90)
{
pXRFTimer.Stop();
}
else
{
//show time elapsed
}
}
答案 0 :(得分:0)
我不确定您的应用程序的结构,但是可以通过类似这样的方法来计算经过的时间
DateTime startUtc;
private void ScanpXRF()
{
startUtc = DateTime.NowUtc;
(...)
//START action to be measured here!
}
private static void pXRFTimer_Tick(Object sender, EventArgs e)
{
var elapsed = DateTime.NowUtc - startUtc;
var elapsedSeconds = elapsed.TotalSeconds; // double so you may want to round.
}