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?
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.
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.
You can use await Task.Delay(500);
without blocking the thread like Sleep
does, and with a lot less code than a Timer.
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.
It the method in question is executing on a different thread than the rest of your application, then do the following:
Thread.Sleep(500);
System.Threading.Thread.Sleep(500);
Update
This won't block the rest of your application, just the thread that is running your method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With