santBart santBart - 7 months ago 83
C# Question

c# wait for a while without blocking

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?


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 here
    t.AutoReset = true; //Stops it from repeating
    t.Elapsed += new ElapsedEventHandler(TimerElapsed);

void TimerElapsed(object sender, ElapsedEventArgs e)
    Console.WriteLine("Hello, world!");

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