dviddddd dviddddd - 1 year ago 95
C# Question

Add multiple timer with for loop C#

I need 40 timers in my program but I want to create these dynamically.

System.Timers.Timer timermatrix1=new System.Timers.Timer();
timermatrix1.Enabled = true;
timermatrix1.Interval = 10;
timermatrix1.Elapsed += Timermatrix1_Elapsed;

private void Timermatrix1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)

This code can create one timer but I need 40.So How can I do?

Answer Source

Create an array and initialize them in a loop:

System.Timers.Timer[] timerMatrix = new System.Timers.Timer[40];

for(int i=0; i < 40; i++){
    timerMatrix[i] = new System.Timers.Timer() {
        Enabled = true,
        Interval = 10

    timerMatrix[i].Elapsed += (sender, e) => {
        //TODO: add timer logic
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download