C# 如何在计时器运行后设置状态

C# 如何在计时器运行后设置状态,c#,timer,C#,Timer,我的问题可能很简单。在一个c#项目中,我试图在单击事件中设置不同类中实例的状态。问题是,我想在一段时间后再做这件事,而没有任何经验,我发现这很难做到 提前谢谢 我的代码如下: public void button1_Click(object sender, EventArgs e) { kruispunt.zPad1.voetstoplicht1.setStatus(StoplichtStatus.Rood); kruispunt.zPad1.voetstoplicht2.set

我的问题可能很简单。在一个c#项目中,我试图在
单击事件中设置不同类中实例的状态。问题是,我想在一段时间后再做这件事,而没有任何经验,我发现这很难做到

提前谢谢

我的代码如下:

public void button1_Click(object sender, EventArgs e)
{
    kruispunt.zPad1.voetstoplicht1.setStatus(StoplichtStatus.Rood);
    kruispunt.zPad1.voetstoplicht2.setStatus(StoplichtStatus.Rood);            
    this.Refresh();            
}

最简单的方法是使用
async
(假设您使用的是C#5):

另一个选项是使用
计时器

public void button1_Click(object sender, EventArgs e)
{
    var timer = new System.Windows.Forms.Timer { Interval = 5000 };
    timer.Tick += delegate
    {
        timer.Dispose();
        kruispunt.zPad1.voetstoplicht1.setStatus(StoplichtStatus.Rood);
        kruispunt.zPad1.voetstoplicht2.setStatus(StoplichtStatus.Rood);
        this.Refresh();
    }
    timer.Start();
}

请注意,我使用的是Windows窗体计时器,而不是
System.Timers.timer
System.Threading.timer
;这是因为事件必须发生在UI线程中,否则调用
刷新
将失败。

最简单的方法是使用
async
(假设您使用的是C#5):

另一个选项是使用
计时器

public void button1_Click(object sender, EventArgs e)
{
    var timer = new System.Windows.Forms.Timer { Interval = 5000 };
    timer.Tick += delegate
    {
        timer.Dispose();
        kruispunt.zPad1.voetstoplicht1.setStatus(StoplichtStatus.Rood);
        kruispunt.zPad1.voetstoplicht2.setStatus(StoplichtStatus.Rood);
        this.Refresh();
    }
    timer.Start();
}
请注意,我使用的是Windows窗体计时器,而不是
System.Timers.timer
System.Threading.timer
;这是因为事件必须发生在UI线程中,否则调用
Refresh
将失败