Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 486
73est Avatar asked Nov 26 '25 10:11

73est


1 Answers

Use async/await approach.
Make your method async - below example for eventhandler of button click

private async void ButtonClick(object sender, EventArgs e)
{
    clear();
    coinRefundComplete.Visible = true;
    state = 0;

    await Task.Delay(4000);
    clear();

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

On line await Task.Delay(4000); UI thread will be release, which will update all changes were made before. After 4 seconds method will continue executing on the UI thread.

like image 90
Fabio Avatar answered Nov 27 '25 22:11

Fabio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!