Timers in C#, how to control whats being sent to the timer1_tick
In this following function, that gets executed whenever I do
timer1.Enabled = true
private void timer1_Tick(object sender, EventArgs e)
{
//code here
}
How can I control what gets send to the (object sender, EventArgs e)
?
I want to use 开发者_运维技巧its parameters
The method signature is fixed, so you can't pass extra parameters to it. However, the this
reference is valid within the event handler, so you can access instance members of the class (variables declared inside class
but outside of any method).
1) You can use Tag property of your timer as userState
void timer1_Tick(object sender, EventArgs e)
{
Timer timer = (Timer)sender;
MyState state = timer.Tag as MyState;
int x = state.Value;
}
2) You can use field of reference type to read it in Timer's thread
void timer1_Tick(object sender, EventArgs e)
{
int x = _myState.Value;
}
3) You can use System.Threading.Timer to pass state to timer event handler
Timer timer = new Timer(Callback, state, 0, 1000);
If you want to access Timer's property in the timer1_tick method, you could do via
this.timer1 ex: this.timer1.Enabled =false;
or
Timer timer = (Timer) sender;
timer.Enabled = false;
Maybe you could make an inheritance from timer class, and there, cast the tick event (from Timer) into a tick_user event or something like this that modify de params and put into EventArgs (this is the right place to do, not in sender) other parameters you want. Also you can make a method with more or less parameters, it's up to you.
Hope this helps.
精彩评论