我的应用程序中有一系列标签 -
Label[] labels = new Label[8];
Run Code Online (Sandbox Code Playgroud)
我想按顺序改变循环中那些的背景颜色 -
private void btnPrepare_Click(object sender, EventArgs e)
{
Application.DoEvents();
for (int i = 0; i < 8; i++)
{
labels[i].BackColor = System.Drawing.Color.Red;
System.Threading.Thread.Sleep(2000);
}
}
Run Code Online (Sandbox Code Playgroud)
但所有变化都是一起出现的,而不是顺序出现的.
有帮助吗?
就像这样(快速修正):
private void btnPrepare_Click(object sender, EventArgs e) {
//DONE: foreach - no magic numbers (8)
foreach (var lbl in labels) {
lbl.BackColor = System.Drawing.Color.Red;
lbl.Update(); // <- Update == force label repainting
System.Threading.Thread.Sleep(2000);
}
}
Run Code Online (Sandbox Code Playgroud)
Application.DoEvents()是邪恶的:当你想要画画时,它会翻译所有事件,例如,形式关闭.
一个更好的办法是使用Task,而不是Thread:
// async: we're going to put await in the method
private async void btnPrepare_Click(object sender, EventArgs e) {
//DONE: foreach - no magic numbers (8)
foreach (var lbl in labels) {
lbl.BackColor = System.Drawing.Color.Red;
// await: No need in force repainting, messages translating etc.
await Task.Delay(2000);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
210 次 |
| 最近记录: |