c# Timer (System.Timers.Timer) is used to periodically trigger an event within windows form application. I would like to call function (for example logger() function) within the even handler. logger() is not a static method.
The function assigned to ElapsedEventHandler is a static function and therefore cannot call non-static methods. Code example:
public partial class MainForm : Form {
//...
private MyClass myClass;
//...
}
private void SomeButton_Click(object sender, EventArgs e) {
//...
System.Timers.Timer t = new System.Timers.Timer(5000);
t.Elapsed += new ElapsedEventHandler(OnTimerElapsed);
t.Enabled = true;
//...
}
static void OnTimerElapsed(object sender, ElapsedEventArgs e) {
//...
// here call myClass.doSomething();
//...
}
How would be the correct way to go about this task? I do know that static variables/methods are not possible to be used within the OnTimerElapsed() - that is clear. I mainly ask to check whether there is another way of calling OnTimerElapsed(), maybe a non-static method or another timer type or handler method? Or if there is a way to pass the instance of myClass to the OnTimerElapsed()
Edit: it would be preferable to keep the myClass non-static, that is why this question.