I am trying to use System.Timers.Timer to fire events every second. Example below (Console application)
static void Main(string[] args)
{
var timer = new System.Timers.Timer(1000);
timer.Elapsed += (sender, e) => PrintToConsole();
timer.Start();
Console.ReadLine();
}
private static void PrintToConsole()
{
var randomInt = new Random().Next(1000);
Console.WriteLine(randomInt);
Thread.Sleep(2000);
Console.WriteLine(randomInt);
}
Since there is a sleep in PrintToConsole(), the random number generated at the beginning of function wont be the next line printed, so it will be like below
12 45 56 12 67
That makes sense as the subsequent threads from elapsed event take over when one thread blocks.
I need the event handlers to honour the event order(the second handler should follow the first handler and so on). How is it possible?