Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call instance method from static time callback

Tags:

c#

timer

I have a timer within a class, and when this timer fires I want to call an instance method of this class. How do I access this from the static timer callback method?

private void ClassInstanceMethod()
{
}

public static void TimerFired(object source, ElapsedEventArgs e)
{
    // Want to call ClassInstanceMethod() here
}

private void startTimer()
{
    timer = new Timer();
    timer.Interval = 1000;
    timer.Elapsed += new ElapsedEventHandler(TimerFired);
    timer.AutoReset = false;
    timer.Enabled = true;
}

Solved
I had the misconception that TimerFired had to be static - which it does not.

like image 483
Egil Avatar asked May 19 '26 12:05

Egil


1 Answers

You can't. The source parameter is the Timer object, and the ElapsedEventArgs object doesn't contain any reference to the instance of your class. As was discussed in the comments, you can make the TimerFired method non-static (i.e., instance), and from there you'll be able to safely call ClassInstanceMethod and other instance methods from the class.

like image 90
carlosfigueira Avatar answered May 22 '26 01:05

carlosfigueira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!