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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With