Daniel
Daniel

Reputation: 3364

How can I make my application wait for specific amount of time?

I want to add some Items to a listbox, but the thing is, I want the application waits for 500ms after adding each item then adds the next item; so I used the code below:

    reduction_list.Items.Add("ID");
    System.Threading.Thread.Sleep(500);

    reduction_list.Items.Add("Name");
    System.Threading.Thread.Sleep(500);

    reduction_list.Items.Add("City");
    System.Threading.Thread.Sleep(500);

    reduction_list.Items.Add("Major");

but the application waits for 1500ms and adds the whole 4 items all together.

Upvotes: 3

Views: 644

Answers (2)

Jalal Said
Jalal Said

Reputation: 16162

That is because you didn't update the interface after adding, so just add this after each call:

reduction_list.Invalidate();
reduction_list.Update(); 

The problem here is that you didn't give the interface time to update itself, since you are executing the code at UI thread. So adding Invalidate() or Refresh() after each add will cause the application to refresh the reduction_list view.

Upvotes: 1

Anders Abel
Anders Abel

Reputation: 69250

The problem is that you are making the UI thread sleep, which means that it never gets a chance to redraw the UI with the new items.

You should use a timer instead. (The exact timer class to use depends on what UI framework you are using - Winforms or WPF. Please tag your question appropriately.)

Upvotes: 1

Related Questions