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

İ want to wait one second before printing my grid cells with this code, but it isn't working. What can i do?

Drenmi
  • 8,492
  • 4
  • 42
  • 51
Selçuklu Ebrar
  • 2,059
  • 3
  • 14
  • 11

12 Answers12

273

Is it pausing, but you don't see your red color appear in the cell? Try this:

dataGridView1.Rows[x1].Cells[y1].Style.BackColor = System.Drawing.Color.Red;
dataGridView1.Refresh();
System.Threading.Thread.Sleep(1000);
Matt Dawdy
  • 19,247
  • 18
  • 66
  • 91
50

Personally I think Thread.Sleep is a poor implementation. It locks the UI etc. I personally like timer implementations since it waits then fires.

Usage: 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();
}
Elian Kamal
  • 532
  • 7
  • 20
Mark Rowe
  • 919
  • 9
  • 7
34

Wait function using timers, no UI locks.

public void wait(int milliseconds)
{
    var timer1 = new System.Windows.Forms.Timer();
    if (milliseconds == 0 || milliseconds < 0) return;

    // Console.WriteLine("start wait timer");
    timer1.Interval = milliseconds;
    timer1.Enabled  = true;
    timer1.Start();

    timer1.Tick += (s, e) =>
    {
        timer1.Enabled = false;
        timer1.Stop();
        // Console.WriteLine("stop wait timer");
    };

    while (timer1.Enabled)
    {
        Application.DoEvents();
    }
}

Usage: just placing this inside your code that needs to wait:

wait(1000); //wait one second
AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
Said
  • 473
  • 7
  • 11
  • Just a suggestion. If you multiply the min with 60000, the parameter name will be more meaningful. timer1.Interval = min * 60000; – Golda Nov 16 '18 at 06:28
  • 1
    Yes, you are right it should be milliseconds instead of min. I will update the name. Thanks – Said Nov 26 '18 at 13:40
26

.Net Core seems to be missing the DispatcherTimer.

If we are OK with using an async method, Task.Delay will meet our needs. This can also be useful if you want to wait inside of a for loop for rate-limiting reasons.

public async Task DoTasks(List<Items> items)
{
    foreach (var item in items)
    {
        await Task.Delay(2 * 1000);
        DoWork(item);
    }
}

You can await the completion of this method as follows:

public async void TaskCaller(List<Item> items)
{
    await DoTasks(items);
}
Rich Hildebrand
  • 1,607
  • 17
  • 15
10

The Best way to wait without freezing your main thread is using the Task.Delay function.

So your code will look like this

var t = Task.Run(async delegate
{              
    dataGridView1.Rows[x1].Cells[y1].Style.BackColor = System.Drawing.Color.Red;
    dataGridView1.Refresh();
    await Task.Delay(1000);             
});
amitklein
  • 1,302
  • 6
  • 23
  • This has the potential to confuse readers. Original question did not specify their print code and you assumed it is suppose to be running after the dataGridView1 code. I would add some extra comments after the Task.Delay to indicate that the waiting is done there. Also, the whole construct does not block so users that are not familiar with Task.Run might assume that the Task.Run command will wait in itself (which it doesn't). – Andreas Pardeike Nov 09 '21 at 20:02
  • Hey, thanks for the input but I don't think I fully understand what you want me to do so if you can just edit this answer this will be great! – amitklein Nov 22 '21 at 22:16
6

I feel like all that was wrong here was the order, Selçuklu wanted the app to wait for a second before filling in the grid, so the Sleep command should have come before the fill command.

    System.Threading.Thread.Sleep(1000);
    dataGridView1.Rows[x1].Cells[y1].Style.BackColor = System.Drawing.Color.Red;
Colin D
  • 69
  • 1
  • 2
3

Busy waiting won't be a severe drawback if it is short. In my case there was the need to give visual feedback to the user by flashing a control (it is a chart control that can be copied to clipboard, which changes its background for some milliseconds). It works fine this way:

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;
....
ChrisW
  • 39
  • 1
3

If using async

await Task.Delay(new TimeSpan(0, 0, 1));

else

Thread.Sleep(new TimeSpan(0, 0, 1));
v.t.
  • 41
  • 2
1

use dataGridView1.Refresh(); :)

1

Try this function

public void Wait(int time) 
{           
    Thread thread = new Thread(delegate()
    {   
        System.Threading.Thread.Sleep(time);
    });
    thread.Start();
    while (thread.IsAlive)
    Application.DoEvents();
}

Call function

Wait(1000); // Wait for 1000ms = 1s
1

This solution is short and, so far as I know, light and easy.

public void safeWait(int milliseconds)
{
    long tickStop = Environment.TickCount + milliseconds;
    while (Environment.TickCount < tickStop)
    {
        Application.DoEvents();
    }
}
Dave
  • 3,093
  • 35
  • 32
-4

Maybe try this code:

void wait (double x) {
    DateTime t = DateTime.Now;
    DateTime tf = DateTime.Now.AddSeconds(x);

    while (t < tf) {
        t = DateTime.Now;
    }
}
MarredCheese
  • 17,541
  • 8
  • 92
  • 91
  • 5
    This is a valid solution. However, you should add a description of its benefits and harms, such as mentioning that because it is a busy-waiting solution, it will take up CPU time. –  Nov 13 '14 at 21:12
  • 1
    The shorter solution is the better solution – BASEER ULHASSAN Jan 23 '17 at 13:02
  • 3
    @BASEERULHASSAN If that were true, we'd all be coding in BrainFuck. Good code is readable code with fast performance speeds that does what is needed to do without negative side-effects. – Tigerrrrr Dec 26 '20 at 02:08