定时器被中断

mou*_*kin -2 .net c# timer stream

我在Windows窗体应用程序中的Timer有问题.需要Timer记录归档时间的归档程序.然而有什么东西打断了计时器?

我怀疑是流.关于什么可能导致计时器中断的任何建议?

public partial class Form1 : Form
{
    int timerCounter = 0;
    System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();

    public Form1()
    {
        InitializeComponent();
        timer.Interval = 1000; 
        timer.Enabled = true;
    }

    public void button2_Click(object sender, EventArgs e)
    {
        timer.Start();
        timer.Tick += new EventHandler(timer1_Tick); 

        // code for archiving, streams

        timer.Stop(); 

        MessageBox.Show("Archive was created! :)");
    }

    public void timer1_Tick(object sender, EventArgs e)
    {
        this.label7.Text = (++timerCounter).ToString();
    }  
Run Code Online (Sandbox Code Playgroud)

}

Tho*_*mar 7

Windows窗体计时器不是多线程的.这意味着,tick事件仅在程序空闲时触发(通过其消息队列接收消息).在你的程序中,似乎并非如此.您可以轻松地检查这一点:如果您的用户界面在归档过程中有响应,那么Forms.Timer运行也会出现问题,而问题则出在其他地方.如果它没有响应,则表单(以及结果的计时器)被阻止(应用程序的消息队列中没有消息被处理).

有两种方法:

  1. 要执行您想要实现的目标,您可以使用System.Timers.TimerSystem.Threading.Timer,因为它们在后台异步运行.然而,UI仍然不会更新(计时器方法会停止),因为UI仍然被阻止(参见上文).
  2. 另一种方法是使用后台工作程序进行存档过程(然后在另一个线程中运行).UI和计时器保持响应.