Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 810
Alon B Avatar asked Jan 23 '11 10:01

Alon B


People also ask

What is timer in C?

TIMER. C: These functions allow one to obtain user and system timings for arbitrary blocks of code. If a code block is called repeatedly during the course of program execution, the timer functions will report the block's cumulative execution time and the number of calls.

What is timer explain?

: one that times: such as. : timepiece. especially : a stopwatch for timing races. : timekeeper. : a device (such as a clock) that indicates by a sound the end of an interval of time or that starts or stops a device at predetermined times.

What is the use of timer give example?

Furthermore, if we want to execute an application after a specific amount of time, we can use the Timer Control. Once the timer is enabled, it generates a tick event handler to perform any defined task in its time interval property.


2 Answers

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

like image 125
Zooba Avatar answered Oct 19 '22 22:10

Zooba


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);
like image 36
Sergey Berezovskiy Avatar answered Oct 20 '22 00:10

Sergey Berezovskiy