Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to wait for a certain time (say 10 seconds) in C#?

Tags:

c#

I want to wait for 15 seconds, then the control should resume from the next statement.

I don't have anything else to do while waiting (Just waiting).

I know that there is Thread.Sleep(15000). What I don't know is the best method to wait? What are the limitations of this?

The code would be like this:

Method()
{
   statement 1;
   statement 2;
   //WaitFor 15 secs here;
   statement 3;
}
like image 398
Naresh Avatar asked Aug 24 '09 06:08

Naresh


1 Answers

The disadvantage of Thread.Sleep is if this is called in your GUI thread (the thread that processes GUI events, for example, a button click handler method, or a method called from a button click handler, etc.) then you application will appear to freeze and be nonresponsive for those 15 seconds.

It would be perfectly fine if you had explicetly created a seperate thread and called Thread.Sleep in it, assuming you don't mind that thread not doing anything for 15 seconds.

The alternative would be to create a Timer and start it after stmt 2, and place stmt 3 in the Tick event handler for the timer, and also stop the timer in that handler.

like image 95
AaronLS Avatar answered Oct 13 '22 00:10

AaronLS