Registration for expired timer events

I want to create a class that initializes a timer, which will be used as the central core for other members of the class to register itself for the timer event. My problem is that I really don’t know how to set the past timer event to other classes. One solution that I think might work is that I simply set the timer as a public property that will return a timer object, and I can trigger a timer-passed event from that object, for example:

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

But with this decision, I will expose the entire timer that I do not want. How to pass a method in the MyAppTimer class that will register a method with an internal event timer? Does this have anything to do with delegates? Maybe something like:

public void RegisterHandler(someStuffGoesHere) //What do I pass in here?
{
  timer.Elapsed += someStuffGoesHere;
}
+3
source share
3 answers

You can create an event with explicit access:

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

Clients of your class can subscribe directly to the TimerElapsed event:

appTimer.TimerElapsed += SomeHandlerMethod;

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

EDIT: note that with this approach, the sender parameter value will be a Timer object, not a MyAppTimer object. If this is a problem, you can do it 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);
}
+3
source

As others have pointed out, exposing the event is probably the way you want, but to answer your question about the type that is required in your RegisterHandler method, it will look something like this:

using System.Timers;

...snip...

public void RegisterHandler(ElapsedEventHandler callback)
{
  timer.Elapsed += callback;
}
+2

, :

class A
{
    public event EventHandler<EventArgs> Elapsed;

    private void OnElapsed()
    {
         if(Elapsed!=null)
                 Elapsed(new EventArgs());
    }
}

in the OnElapsed personal method you have an example of how to raise an event. Then you use class A in the same way as Timer.

0
source

Source: https://habr.com/ru/post/1709181/


All Articles