我的问题可能很简单。在c#项目中,我试图在click事件中在不同的类中设置实例的状态。麻烦的是,我想在一段时间过去之后再这样做,如果没有任何c#经验,我发现很难做到这一点。
提前谢谢!!
我的代码如下:
public void button1_Click(object sender, EventArgs e)
{
kruispunt.zPad1.voetstoplicht1.setStatus(StoplichtStatus.Rood);
kruispunt.zPad1.voetstoplicht2.setStatus(StoplichtStatus.Rood);
this.Refresh();
}发布于 2013-10-26 23:03:53
最简单的方法是使用async (假设您使用的是C# 5):
public async void button1_Click(object sender, EventArgs e)
{
await Task.Delay(Timespan.FromSeconds(5));
kruispunt.zPad1.voetstoplicht1.setStatus(StoplichtStatus.Rood);
kruispunt.zPad1.voetstoplicht2.setStatus(StoplichtStatus.Rood);
this.Refresh();
}另一种选择是使用Timer
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的调用将失败。
https://stackoverflow.com/questions/19612823
复制相似问题