Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# event handler being added twice

This is a fictional example but I was wandering what happens if the InitialiseTimer function gets called twice. Does the timer elapsed function get triggered twice. Will this change if the functions are made static?

    private static void InitialiseTimer()
    {
            TheTimer = new System.Timers.Timer();
            TheTimer.Interval = 400;
            TheTimer.Elapsed += new ElapsedEventHandler(TheTimer_Elapsed);
            TheTimer.AutoReset = false;
    }   

    public void TheTimer_Elapsed(object sender, ElapsedEventArgs e)
    {
        //Do stuff in here
    }

I was going to use below to prevent this

Has an event handler already been added?

Thanks, Richard

like image 266
probably at the beach Avatar asked Jun 13 '26 14:06

probably at the beach


1 Answers

If you register the event handler twice, it will be invoked twice every time the event is raised.

This won't change if you make TheTimer_Elapsed static, because you'll still hold two references to this static method.

In most cases there's no need to write compicated things like what Blair Conrad posted in the question you linked to. Just don't forget to use -= every time you have += and you'll be safe.

like image 114
Ilya Kogan Avatar answered Jun 15 '26 03:06

Ilya Kogan