在运行程序中等待一秒钟

dataGridView1.Rows[x1].Cells[y1].Style.BackColor = System.Drawing.Color.Red; System.Threading.Thread.Sleep(1000); 

我想在打印我的网格单元格之前等待一秒钟,但是这不起作用。 我能做什么?

它是否暂停,但你没有看到你的红色出现在细胞中? 尝试这个:

 dataGridView1.Rows[x1].Cells[y1].Style.BackColor = System.Drawing.Color.Red; dataGridView1.Refresh(); System.Threading.Thread.Sleep(1000); 

我个人认为Thread.Sleep是一个糟糕的实现。 它locking用户界面等,我个人喜欢定时器的实现,因为它等待火灾。

用法: DelayFactory.DelayAction(500, new Action(() => { this.RunAction(); }));

 //Note Forms.Timer and Timer() have similar implementations. public static void DelayAction(int millisecond, Action action) { var timer = new DispatcherTimer(); timer.Tick += delegate { action.Invoke(); timer.Stop(); }; timer.Interval = TimeSpan.FromMilliseconds(millisecond); timer.Start(); } 

使用dataGridView1.Refresh(); 🙂

忙碌的等待不会是一个严重的缺点,如果它是短暂的。 在我的情况下,需要通过闪烁控件(这是一个图表控件,可以复制到剪贴板,其背景改变几毫秒),给用户一个视觉反馈。 它可以很好地工作:

 using System.Threading; ... Clipboard.SetImage(bm); // some code distribution_chart.BackColor = Color.Gray; Application.DoEvents(); // ensure repaint, may be not needed Thread.Sleep(50); distribution_chart.BackColor = Color.OldLace; .... 

也许试试这个代码

  void wait (int x){ DateTime t = DateTime.Now; DateTime tf = DateTime.Now.AddSeconds(x); while (t < tf) { t = DateTime.Now; } }