73est 73est - 25 days ago 19
C# Question

Code not executing before thread sleep?

I do this:

clear();
coinRefundComplete.Visible = true;
state = 0;

System.Threading.Thread.Sleep(4000);
clear();

greeting.Visible = true;
rate.Visible = true;
refundTicket.Visible = true;
currentTime.Visible = true;


I expect the
coinRefundComplete
Text (it is a label) to appear for 4 seconds, then get cleared by a method I defined with clear(), and then some other stuff happens. Instead after I clear my form with the first clear(), my form is blank for 4 seconds, then finishes properly.

Answer

Call Control.Update or Control.Refresh after making it visible and before going to sleep so that the GUI thread is able to show changes before it goes to sleep.

clear();
coinRefundComplete.Visible = true;
label1.Update();
state = 0;    
System.Threading.Thread.Sleep(4000);
clear();

You should be carefull while using Thread.Sleep, In your case it is GUI thread and GUI will be irresponsive for the time you sleep. Knowing the reason why you want to block thread could bring some other better suggestion.

Comments