Hope the following solution helps!
Problem:
The following code always works as expected by showing the current clock time.
class Program
{
static void TimerProcedure(object param)
{
Console.Clear();
Console.WriteLine(DateTime.Now.TimeOfDay);
GC.Collect();
}
static void Main(string[] args)
{
Console.Title = "Desktop Clock";
Console.SetWindowSize(20, 2);
Timer timer = new Timer(TimerProcedure, null,
TimeSpan.Zero, TimeSpan.FromSeconds(1));
Console.ReadLine();
}
}
However, if you run the same code in release mode, it shows current time only for the first time but it never updates after that.
Solution
A simple tweak by adding GC.KeepAlive(object) will make it work in Release mode also as expected. Refer to code below.
class Program
{
static void TimerProcedure(object param)
{
Console.Clear();
Console.WriteLine(DateTime.Now.TimeOfDay);
#region Hidden
GC.Collect();
#endregion
}
static void Main(string[] args)
{
Console.Title = "Desktop Clock";
Console.SetWindowSize(20, 2);
Timer timer = new Timer(TimerProcedure, null,
TimeSpan.Zero, TimeSpan.FromSeconds(1));
Console.ReadLine();
GC.KeepAlive(timer);
}
}
Coming to your specific problem, verify if the scope of timer variable is local to a method. If that is true, you can keep it alive as shown above.
Alternate solution: is making timer a class level static variable