Tell me how the Thread.Sleep(); method works Thread.Sleep(); in such a piece of code, for example

 listBox1.Items.Add("First Item"); Thread.Sleep(5000); listBox1.Items.Add("Second Item"); 

It turns out that when this piece of code is executed, there is a delay first, and then 2 objects are immediately added to the listbox . But it is necessary that the first object be added first, 5 seconds have passed and only then the second one. What am I doing wrong?

    1 answer 1

    In fact, the above code works exactly as you wrote: first the first record is added, then the stream is delayed, then the second record is added. But you see another result: first, a delay, then the addition of two records. This is due to the fact that you delay in the main, UI, stream. The UI thread has a so-called. message queue that it processes. After adding the first record to this queue, a message is added to draw the text in the control. But since you immediately make a delay, the processing of this queue stops and the thread simply does not have time to draw the first entry in the control. After the delay ends, another message is added to the queue, and the thread draws both entries.

    It is difficult to advise how to fix it, because it is not clear what you want to achieve. Also, making delays (especially in the UI thread) is usually a bad idea. As an option, you can ask the UI thread to process the message queue before the delay:

     listBox1.Items.Add("First Item"); Application.DoEvents(); Thread.Sleep(5000); listBox1.Items.Add("Second Item"); 

    But, I repeat, this is only in order to satisfy curiosity. In a good way, you should get rid of the delay and do what you want in a different way. For example, use a timer or async / await .

    • In general, you answered my questions. Thanks It works. But then got the underwater rock. In fact, I just want to simulate a slight delay in the application. and before adding the 1st element to the listbox, I start a timer in which a simple message is displayed, ala "wait a couple of seconds", and so it either starts only after the application has slept for 5 seconds, it starts up toli, but does not tick has time. I would be grateful if you also leave explanations on this submerged stone. - Pyrejkee
    • @KirillKiryanchikov make this a separate question and add enough code to it to play. - andreycha