Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# time delay on application

Tags:

c#

delay

timer

I am currently developing an application, I would like to implement a time delay. I don't want to use System.Threading.Thread.Sleep(x); as I read this stalls the thread (UI freezes)

The code I have currently written is:

public void atimerdelay()
{
    lblStat.Text = "In the timer";
    System.Timers.Timer timedelay;
    timedelay = new System.Timers.Timer(5000);
    timedelay.Enabled = true;
    timedelay.Start();
}

I know atimerdelay() does get called (using lblStat), but their is no delay of 5 seconds. I have read http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx but I can't work out why the above code is not working.

Additional information - (added for Hamlet Hakobyan)

The application is a 'card checker' application (University project - no real information is used or stored). Once the user has filled out all the relevant and click 'check' a list of validation methods are called. Before any of these are called a ping is carried out to make sure a live internet connection is on the computer. I want to add a slight delay between the ping and the starting of the validation.

like image 480
Dan1676 Avatar asked Feb 11 '26 01:02

Dan1676


2 Answers

How about:

await Task.Delay(5000)

? It won't block UI thread and looks pretty good!

like image 188
Nagg Avatar answered Feb 12 '26 13:02

Nagg


I'll never forget this wonderful snippet. Its suitable for Windows Form Applications, and much more lightweight than creating a Timer.

like image 27
Jason Avatar answered Feb 12 '26 13:02

Jason



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!