Timer.Tick事件处理程序未在Timer中获取事件Timer_Tick

时间:2012-01-05 19:18:23

标签: c# timer

您好我正在使用Web应用程序使用Windows.Forms.Timer。我创建Timer.Tick事件处理程序来处理Timer_Tick但我没有成功。我没有得到任何错误,但我甚至无法得到结果。这是我的代码

     System.Windows.Forms.Timer StopWatchTimer = new System.Windows.Forms.Timer();
    Stopwatch sw = new Stopwatch();

public void StopwatchStartBtn_Click(object sender, ImageClickEventArgs e)
{
    StopWatchTimer.Enabled = true;
    StopWatchTimer.Interval = 1;
    StopWatchTimer.Start();
    this.StopWatchTimer.Tick += new EventHandler(StopWatchTimer1_Tick);
    sw.Start();
}


protected void StopWatchStopBtn_Click(object sender, ImageClickEventArgs e)
{
    StopWatchTimer.Stop();
    sw.Reset();
    StopWatchLbl.Text = "00:00:00:000";
}

public void StopWatchTimer1_Tick(object sender,EventArgs e)
{
    TimeSpan elapsed = sw.Elapsed;
    StopWatchLbl.Text = string.Format("{0:00}:{1:00}:{2:00}:{3:00}", 
                            Math.Floor(elapsed.TotalHours), 
                            elapsed.Minutes, 
                            elapsed.Seconds, 
                            elapsed.Milliseconds);
}

3 个答案:

答案 0 :(得分:4)

来自the MSDN documentation for Windows Forms Timer(强调我的):

实现以用户定义的间隔引发事件的计时器。此计时器已针对Windows窗体应用程序进行了优化,必须在窗口中使用

此计时器不适用于Web应用程序。您需要使用其他类,例如System.Timers.Timer。然而,这有它自己的陷阱。

答案 1 :(得分:1)

您是否尝试在启动计时器之前定义Tick事件?

this.StopWatchTimer.Tick += new EventHandler(StopWatchTimer1_Tick);    
StopWatchTimer.Start();

答案 2 :(得分:1)

public partial class TestFrom : Form
{
    private Thread threadP;
    private System.Windows.Forms.Timer Timer = new System.Windows.Forms.Timer();
    private string str;

    public TestFrom()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        Timer.Interval =100;
        Timer.Tick += new EventHandler(TimeBussiness);
        Timer.Enabled = true;
        Timer.Start();
        Timer.Tag = "Start";
    }

    void TimeBussiness(object sender, EventArgs e)
    {
        if (threadP.ThreadState == ThreadState.Running)
        {
            Timer.Stop();
            Timer.Tag = "Stop";
        }
        else
        {
            //do my bussiness1;
        }
     }

    private void button3_Click(object sender, EventArgs e)
    {
        ThreadStart threadStart = new ThreadStart(Salver);
        threadP= new Thread(threadStart);
        threadP.Start();
    }

    private void Salver()
    {
        while (Timer.Tag == "Stop")
        {

        }
        //do my bussiness2;
        Timer.Start();
        Timer.Tag = "Start";
    }
}
相关问题