为什么winforms秒表的时间慢?

时间:2014-04-30 14:56:49

标签: c# .net winforms

我创建了一个小小的winforms程序作为一个小秒表程序。我的主要问题是时间变得缓慢。
例如,我的秒表程序通过1秒需要大约3.5秒,我想弄清楚是否有更好的方法来处理时间?

我试图包含所有相关且仅包含代码的相关部分。

全局变量:

System.Windows.Forms.Timer microTimer;
EventHandler microTick;
AlertBox box;
string message;
Stopwatch watch;

设置定时器的方法

private void SetTimer(int miliseconds)
    {
        microTimer.Interval = miliseconds;
        microTimer.Enabled = true;
        microTimer.Tick += microTick;
        microTimer.Start();
    }

我的事件逻辑背后的理论是我的计时器上的每个刻度,它会检查秒表上的时间并使用已用时间更新表格上的标签。

microTick = (m_sender, m_e) =>
            {
                TimeSpan t = new TimeSpan(watch.ElapsedTicks);
                lblTimeDisplay.Text = t.Minutes + " : " + t.Seconds + " : " + t.Milliseconds;
            };

这是我的点击事件!

private void btnStart_Click(object sender, EventArgs e)
    {
        SetTimer(1); //I copied this earlier in the message.
        watch.Start();
    }

由于

2 个答案:

答案 0 :(得分:3)

1:最好在启动计时器之前启动秒表......而不是在......之后启动秒表。

2:为了在表单上正确显示时间,你需要在一个单独的线程上运行计时器的滴答...以1 ms的间隔运行你的计时器将循环如此之快以至于它将锁定显示线程因此,后端的“UpdateDisplay”调用将无法快速启动以刷新屏幕以准确表示值,因为它们发生变化...为了确认这一点,请尝试SetTimer(1000)...然后它每1秒准确显示......

了解如何在谷歌中为C#查找线程。

答案 1 :(得分:0)

以下是根据需要运行的代码的基本版本。我不得不在新线程内部创建秒表,使其以正常速度运行。

我的使用:

using System.Threading; 

主要代码:

全局变量:

private new Thread starter;
private bool isThreadRunning = false;

点击活动:

private void button1_Click(object sender, EventArgs e)
{
    this.isThreadRunning = true;
    //create new thread to run stopwatch in
    this.starter = new Thread(new ThreadStart(this.HandleTime)); 
    this.starter.Start();
}

private void button2_Click(object sender, EventArgs e)
{
    //cause the thread to end itself
    this.isThreadRunning = false;
}

在线程内部运行的代码

//HandleTime is inside the new thread
private void HandleTime()
{
    Stopwatch threadStopwatch = new Stopwatch();
    TimeSpan timespan;
    threadStopwatch.Start();
    while (this.isThreadRunning)
    {
        timespan = threadStopwatch.Elapsed;
        //using invoke to update the label which is in the original thread 
        //and avoid a cross thread exception
        if (this.InvokeRequired)
            {
                //read up on lamda functions if you don't know what this is doing
                this.Invoke(new MethodInvoker(() => 
                    label1.Text = timespan.Minutes + " : " + timespan.Seconds + " : " + timespan.Milliseconds
                    ));
            }
            else
            {
                label1.Text = timespan.Minutes + " : " + timespan.Seconds + " : " + timespan.Milliseconds;
            }
    }

}