Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for a while without blocking main thread

I wish my method to wait about 500 ms and then check if some flag has changed. How to complete this without blocking the rest of my application?

like image 978
santBart Avatar asked Dec 13 '11 21:12

santBart


People also ask

What is thread wait in C#?

In C#, Thread class provides the Join() method which allows one thread to wait until another thread completes its execution. If t is a Thread object whose thread is currently executing, then t. Join() causes the current thread to pause its execution until thread it joins completes its execution.


5 Answers

Thread.Sleep(500) will force the current thread to wait 500ms. It works, but it's not what you want if your entire application is running on one thread.

In that case, you'll want to use a Timer, like so:

using System.Timers;  void Main() {     Timer t = new Timer();     t.Interval = 500; // In milliseconds     t.AutoReset = false; // Stops it from repeating     t.Elapsed += new ElapsedEventHandler(TimerElapsed);     t.Start(); }  void TimerElapsed(object sender, ElapsedEventArgs e) {     Console.WriteLine("Hello, world!"); } 

You can set AutoReset to true (or not set it at all) if you want the timer to repeat itself.

like image 54
Toneo Avatar answered Oct 04 '22 00:10

Toneo


You can use await Task.Delay(500); without blocking the thread like Sleep does, and with a lot less code than a Timer.

like image 41
MarkovskI Avatar answered Oct 04 '22 01:10

MarkovskI


I don't really understand the question.

If you want to block before checking, use Thread.Sleep(500);

If you want to check asynchronously every x seconds, you can use a Timer to execute a handler every x milliseconds.

This will not block your current thread.

like image 45
Tudor Avatar answered Oct 03 '22 23:10

Tudor


It the method in question is executing on a different thread than the rest of your application, then do the following:

Thread.Sleep(500);
like image 44
Phil Klein Avatar answered Oct 04 '22 01:10

Phil Klein


System.Threading.Thread.Sleep(500);

Update

This won't block the rest of your application, just the thread that is running your method.

like image 33
danludwig Avatar answered Oct 04 '22 00:10

danludwig