开发者

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

开发者 https://www.devze.com 2023-03-31 09:01 出处:网络
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 cod开发者_StackOverflowe below:

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 cod开发者_StackOverflowe 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.


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.


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.)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号