Weenhallo
Weenhallo

Reputation: 364

How to use System.Timers.Timer properly inside a class

I'm trying to learn how to use Timers and I'm having troubles with the elapsed event. What I have is a class where I check some messages from a databatch. But now I want to make a timer where every x period of time check that messages.

I made this code:

public class Program
{
   static void Main(string[] args)
   {
     Message m = new Message();
     m.init();
   }
}

public class Messages{

    private System.Timers.Timer tt;

    public void init()
    { 
       tt = new(_conf.Period);
       tt.Elapsed += new System.Timers.ElapsedEventHandler(TimerElapsed);
       tt.Start();
       Console.ReadLine();
    }

    private void TimerElapsed(object? sender, ElapsedEventArgs e)
    {
      //Console.WriteLine for test it works
      Console.WriteLine(DateTime.UtcNow);
      //check my messages
    }

}

This doesn't work because it never goes inside TimerElapsed. What am I doing wrong?

Thank you

EDIT: even as a field timer doesn't goes inside elapsed event.

EDIT2: well, I found my problem. I was testing the TimerElapsed with a Console.WriteLine(DateTime.UtcNow) inside of it and it only works if i put after all the code on Init a Console.ReadLine(); Ill edit my code again to show it. I don't understad why I need this readLine so if someone could explain to me would be great.

Upvotes: 0

Views: 1277

Answers (1)

Idle_Mind
Idle_Mind

Reputation: 39132

If you don't like the ReadLine() approach, you can use a polling loop like this instead:

  public static void Main (string[] args) {     
    Messages m = new Messages();
    m.init();
    
    ConsoleKeyInfo cki;
    do {
      while (!Console.KeyAvailable) {
        System.Threading.Thread.Sleep(50);
      }
      cki = Console.ReadKey(true);  
    } while (cki.Key != ConsoleKey.Escape);    
  }

This will keep the app alive until the user hits the Escape key.

You should see the timestamps printing at whatever interval you specified.

Upvotes: 1

Related Questions