¿Cómo puedo hacer que mi solicitud espere un tiempo específico?

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.

preguntado el 27 de agosto de 11 a las 14:08

Is this in a asp.net application or a winforms application? -

sorry I didn't make correct tag. it's winforms -

2 Respuestas

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

Respondido 27 ago 11, 18:08

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 Invalidar () or Actualizar() after each add will cause the application to refresh the reduction_list ver.

Respondido 27 ago 11, 18:08

Even if this works, it is never, ever recommended to make the UI freeze - it will prevent any other user interaction. In this case the UI is locked against interactions for 1.5 seconds which in my opinion is far to long. - Anders Abel

@Anders yes I agree, that comes to my mind, but we don't know his requirements, maybe he wanted it to be that why, how knows.. - Jalal Said

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.