简体   繁体   中英

Timer Class In Console Application C#

public class PacketPoller
{
    private Timer m_timer;

    public void Start()
    {
        m_timer = new Timer(OnTick(null), null, 0, 1);
        m_timer.InitializeLifetimeService();
    }

    public Action<Object> OnTick() { }
}

This is my code, however, the timer seems to require a static method, rather than an object-oriented method. What can I do about it? I want to user to be able to create a new Timer and then change it's OnTick to set the method to call. How can I do that?

This is what I've successfully used recently.

        DispatcherTimer timer1stDoze = new System.Windows.Threading.DispatcherTimer();
        timer1stDoze.Tick += new EventHandler(timer1stDoze_Tick);
        timer1stDoze.Interval = new TimeSpan(0, 5, 0);
        timer1stDoze.Start();

I'm guessing that you are using the System.Timers.Timer class.
I would recommend trying with the System.Windows.Forms.Timer class instead. It do not require a static callback function and is a bit easier to work with (easier to debug due to it not being threaded).
This will require a reference to the System.Windows.Forms assembly tho.

timer.Tick += new EventHandler(CallbackFunction);

If you're going to stick with the System.Threading.Timer , have it as you have, but have your PacketPoller have its own event that you'll fire in conjunction:

public class PacketPoller
{
    public event EventHandler Tick;

    private Timer m_timer;

    public void Start()
    {
        m_timer = new Timer(OnTick, null, 0, 1);
        m_timer.InitializeLifetimeService();
    }

    public void OnTick(object state) 
    { 
        var tick = this.Tick;
        if (tick != null)
            tick();
    }
}

Listeners will be wired to your PacketPoller.Tick event rather than the m_timer directly. I'm assuming you don't have a state to bubble through, but if you need to you can pass it through. (notice I modified the method signature of OnTick and your constructor call as well)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM