如何通过C#在线程中使用计时器?

时间:2014-12-11 07:18:00

标签: c# multithreading

当我想在线程中使用计时器时,会出现如下错误:

Error   1   Method name expected

这是我的代码:

 private void Form1_Load(object sender, EventArgs e)
    {
        label1.Text = String.Format("{0:hh:mm:ss tt}", DateTime.Now);
        ParameterizedThreadStart th1 = new ParameterizedThreadStart(timer1_Tick(new object(),new EventArgs()));
        //ThreadStart th1 = new ThreadStart(test);
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        label1.Text = String.Format("{0:hh:mm:ss tt}", DateTime.Now);

    }

此行发生错误:

ParameterizedThreadStart th1 = new ParameterizedThreadStart(timer1_Tick(new object(),new EventArgs()));

1 个答案:

答案 0 :(得分:1)

using System.Timers;

Label l;
private void updateClock(object source, ElapsedEventArgs e)
{
    l.Invoke((MethodInvoker)(() =>
    {
        l.Text = String.Format("{0:hh:mm:ss tt}", DateTime.Now);
    }));

}

private void Form1_Load(object sender, EventArgs e)
{
    l = new Label();
    l.Location = new Point(5, 5);
    this.Controls.Add(l);

    System.Timers.Timer timer = new System.Timers.Timer();
    timer.Elapsed += updateClock;
    timer.Enabled = true;
    timer.AutoReset = true;
    timer.Interval = 1000;
    timer.Start();
}

这就是我想象你想做的事情。