[英]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.