Alon B
Alon B

Reputation: 155

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

Upvotes: 5

Views: 2843

Answers (4)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236238

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);

Upvotes: 3

Neonamu
Neonamu

Reputation: 736

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.

Upvotes: 0

Vijay Sirigiri
Vijay Sirigiri

Reputation: 4711

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;

Upvotes: 0

Zooba
Zooba

Reputation: 11438

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).

Upvotes: 6

Related Questions