Click here to Skip to main content
15,881,173 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
I have these code lines in C#,

so I want to call the function "EventoPeriodico" repeatedly every certain time to save some information, but I also have another functions that I would like to call inside differents threads, and each thread has its own different time. Every function can be call with distincts threads and timers.

C#
hilos = new Thread[Count];

hilos[i] = new Thread(new ThreadStart(EventoPeriodico));
hilos[i].Start();


This is an example, But what if I have more than one Event/action? Because the user decides how many Events or actions he wants. How can I avoid writing every condition for each Event/action?

C#
private void button1_Click(object sender, EventArgs e){

       for (int i = 0; i <= index-1; i++) { 
        timers[i] = new Timer() { Interval = Intervalos[i] }; 
        timers[i].Start(); timers[i].Enabled = true; 
        timers[i].Tag = i; 
        timers[i].Tick += new EventHandler(timer1_Tick); 
        }
     } 

 private void timer1_Tick(object sender, EventArgs e) {

      Timer timer1 = sender as Timer; 
      int index = (int)timer1.Tag; 
      if (index == 0) { 
      label1.Text = cont1+""; 
      cont1++; 
      } 
      if (index == 1) { 
      label2.Text = cont2 + ""; 
      cont2++; 
      } 
   } 
Posted
Updated 25-Jun-14 13:06pm
v2
Comments
PIEBALDconsult 25-Jun-14 20:30pm    
I can't tell which type of Timer you're using. I have always used a System.Timers.Timer .
Sergey Alexandrovich Kryukov 25-Jun-14 21:22pm    
And why using thread and timer at the same time? Why not using a thread with sleep?
What does it mean: "But what if I have more than one Event/action?". Which events (you did not show a single event in your code)? what actions? how "actions" are related to "events"? And so on... The problem is not clear. You can have as many events as you want, what's the problem?
—SA
gggustafson 27-Jun-14 12:27pm    
I tend to agree with Sergey. You can create multiple threads, each of which sleeps independently of the others.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900