[英]Proper way to add delay in my code execution
我正在尝试制作一个非常简单的逻辑游戏。 我们的想法是看到一个带有一定数量的彩色方块(按钮)的矩阵然后隐藏它们,玩家必须点击彩色方块。 因此,在绘制正方形/按钮和返回原始颜色之间需要2秒的延迟。 所有代码都在button_click
事件中实现。
private void button10_Click(object sender, EventArgs e)
{
int[,] tempMatrix = new int[3, 3];
tempMatrix = MakeMatrix();
tempMatrix = SetDifferentValues(tempMatrix);
SetButtonColor(tempMatrix, 8);
if (true)
{
Thread.Sleep(1000);
// ReturnButtonsDefaultColor();
}
ReturnButtonsDefaultColor();
Thread.Sleep(2000);
tempMatrix = ResetTempMatrix(tempMatrix);
}
这是整个代码,但我需要的是在调用SetButtonColor()
和ReturnButtonsDefaultColor()
之间有一些延迟。 我对Thread.Sleep()
所有实验到目前为止都没有成功。 我在某个时刻得到延迟,但彩色方块/按钮从未显示过。
您没有看到按钮更改颜色,因为Sleep
调用会阻止处理消息。
可能最简单的处理方法是使用计时器。 以2秒的延迟初始化定时器,并确保默认情况下禁用它。 然后,您的按钮单击代码启用计时器。 像这样:
private void button10_Click(object sender, EventArgs e)
{
// do stuff here
SetButtonColor(...);
timer1.Enabled = true; // enables the timer. The Elapsed event will occur in 2 seconds
}
而你的计时器的Elapsed事件处理程序:
private void timer1_TIck(object sender, EventArgs e)
{
timer1.Enabled = false;
ResetButtonsDefaultColor();
}
您始终可以使用TPL,这是最简单的解决方案,因为您不需要处理线程上下文或分割代码。
private async void button10_Click(object sender, EventArgs e)
{
int[,] tempMatrix = new int[3, 3];
tempMatrix = MakeMatrix();
tempMatrix = SetDifferentValues(tempMatrix);
SetButtonColor(tempMatrix, 8);
if (true)
{
await Task.Delay(2000);
// ReturnButtonsDefaultColor();
}
ReturnButtonsDefaultColor();
await Task.Delay(2000);
tempMatrix = ResetTempMatrix(tempMatrix);
}
使用计时器 。 而不是你的Thread.Sleep Start()计时器,在tick事件中调用ReturnButtonsDefaultColor()。 您可以使用第二个计时器而不是第二个Thread.Sleep或保存某种状态并在tick事件中使用它。
您可以使用任务:
private void button10_Click(object sender, EventArgs e)
{
int[,] tempMatrix = new int[3, 3];
tempMatrix = MakeMatrix();
tempMatrix = SetDifferentValues(tempMatrix);
SetButtonColor(tempMatrix, 8);
Task.Factory.StartNew(
() =>
{
if (true)
{
Thread.Sleep(1000);
// ReturnButtonsDefaultColor();
}
ReturnButtonsDefaultColor(); //Need to dispatch that to the UI thread
Thread.Sleep(2000);
tempMatrix = ResetTempMatrix(tempMatrix); //Probably that as well
});
}
WPF中的调度与Winforms不同,谷歌应该很容易;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.