Two ways:
- Your
Elapsed
event handler method could be instance one (non-static). In this form, it will get access to the whole instance of its declaring class, via "this" parameter (keyword "this" could be omitted if there is no an ambiguity).
- Make a handler an anonymous method. It will allow you to use the closure feature. The closure will make even the local variable accessible beyond the lifetime of the method adding a handler to the timer's event invocation list. Please see:
http://en.wikipedia.org/wiki/Closure_%28computer_science%29[^].
Warning! Use with care, only when you understand well how it works.
Is it enough or do you need more detail? Please respond if you need them.
[EDIT]
As I can see, it still need some illustrations. First and foremost, instance handler:
class Motor {
System.Timers.Timer timer = new System.Timers.Timer();
int valReg = 30;
void timerHandler(object sender, System.Timers.ElapsedEventArgs e) {
this.valReg++;
valReg++;
}
void SomeTimerSettingMethod() {
timer.Elapsed += timerHandler;
}
}
Now, the approach with closure. It's more delicate:
class Motor {
System.Timers.Timer timer = new System.Timers.Timer();
int valReg = 30;
void SomeTimerSettingMethod() {
timer.Elapsed += (sender, eventArgs) => {
valReg++;
};
}
}
And, finally, the nice combination of anonymous method without direct access to the data members through the closure, but anonymous method freezes up the "real" handler from unused parameters:
class Motor {
System.Timers.Timer timer = new System.Timers.Timer();
int valReg = 30;
void TimerHandler() {
valReg++;
}
void SomeTimerSettingMethod() {
timer.Elapsed += (sender, eventArgs) => { TimerHandler(); }
}
}
In most cases, I would prefer the last combined variant.
Any questions?
—SA