Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Registering for timer elapsed events

I want to create a class that initializes a timer which will be used as a central core for other class members to register themselves for the timer elapsed event. My problem is that I don't really know how to expose the timer elapsed event to other classes. One solution, that I think might work is that I simply expose the timer as a public property which will return the timer object and I can call the timer elapsed event from this object, for example:

MyAppTimer appTimer = new MyAppTimer();
Timer timer = appTimer.GetAppTimer;
timer.Elapsed += SomeMethod;

But with this solution I will be exposing the entire timer which I don't want. How can I pass in a method in the MyAppTimer class which will register the method with the timer's elapsed event internally? Is it something to do with delegates? Maybe something like:

public void RegisterHandler(someStuffGoesHere) //What do I pass in here?
{
  timer.Elapsed += someStuffGoesHere;
}
like image 764
Draco Avatar asked May 10 '26 15:05

Draco


1 Answers

You can create an event with explicit accessors :

public event EventHandler TimerElapsed
{
    add { timer.Elapsed += value; }
    remove { timer.Elapsed -= value; }
}

The clients of your class can subscribe directly to the TimerElapsed event :

appTimer.TimerElapsed += SomeHandlerMethod;

If you want to use a RegisterHandler method as shown in your code, the type of the parameter should be EventHandler

EDIT: note that with this approach, the value of sender parameter will be the Timer object, not the MyAppTimer object. If that's a problem, you can do that instead :

public MyAppTimer()
{
    ...
    timer.Elapsed += timer_Elapsed;
}

private void timer_Elapsed(object sender, EventArgs e)
{
    EventHandler handler = this.TimerElapsed;
    if (handler != null)
        handler(this, e);
}
like image 100
Thomas Levesque Avatar answered May 13 '26 05:05

Thomas Levesque