Call instance method from static time callback
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 ElapsedEventHandl开发者_如何学Goer(TimerFired);
timer.AutoReset = false;
timer.Enabled = true;
}
Solved
I had the misconception thatTimerFired
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.
精彩评论