2013-08-07 9 views
6

Come fermare un timer dopo alcuni numeri di tick o dopo, diciamo, 3-4 secondi?Arresto del timer C# dopo un certo numero di tick automaticamente

Così inizio un timer e voglio dopo 10 tick o dopo 2-3 secondi di fermarsi automaticamente.

Grazie!

+1

Ci sono così tanti timer in C# :-) Quale timer (quale classe/spazio dei nomi). Ci sono ** ** ** 5 timer: http://stackoverflow.com/questions/10317088/why-there-are-5-versions-of-timer-classes-in-net – xanatos

+0

system.windows.forms.timer –

+0

Forse dovresti gradire la mia risposta quando non sei stanco;) –

risposta

9

È possibile mantenere un contatore come

int counter = 0; 

poi in ogni tick si incrementarlo. Dopo il limite puoi fermare il timer. Fai questo nel tuo evento tick

counter++; 
if(counter ==10) //or whatever your limit is 
    yourtimer.Stop(); 
0

Supponendo che si stia utilizzando lo System.Windows.Forms.Tick. Puoi tenere traccia di un contatore e il tempo che vive in questo modo. È un bel modo di usare la proprietà Tag di un timer. Questo lo rende riutilizzabile per gli altri timer e mantiene il codice generico, invece di usare uno int counter definito a livello globale per ogni timer.

questo codice è generico silenzioso in quanto è possibile assegnare questo gestore di eventi per gestire il tempo che vive e un altro gestore di eventi per gestire le azioni specifiche per cui è stato creato il timer.

System.Windows.Forms.Timer ExampleTimer = new System.Windows.Forms.Timer(); 
    ExampleTimer.Tag = new CustomTimerStruct 
    { 
     Counter = 0, 
     StartDateTime = DateTime.Now, 
     MaximumSecondsToLive = 10, 
     MaximumTicksToLive = 4 
    }; 

    //Note the order of assigning the handlers. As this is the order they are executed. 
    ExampleTimer.Tick += Generic_Tick; 
    ExampleTimer.Tick += Work_Tick; 
    ExampleTimer.Interval = 1; 
    ExampleTimer.Start(); 


    public struct CustomTimerStruct 
    { 
      public uint Counter; 
      public DateTime StartDateTime; 
      public uint MaximumSecondsToLive; 
      public uint MaximumTicksToLive; 
    } 

    void Generic_Tick(object sender, EventArgs e) 
    { 
      System.Windows.Forms.Timer thisTimer = sender as System.Windows.Forms.Timer; 
      CustomTimerStruct TimerInfo = (CustomTimerStruct)thisTimer.Tag; 
      TimerInfo.Counter++; 
      //Stop the timer based on its number of ticks 
      if (TimerInfo.Counter > TimerInfo.MaximumTicksToLive) thisTimer.Stop(); 
      //Stops the timer based on the time its alive 
      if (DateTime.Now.Subtract(TimerInfo.StartDateTime).TotalSeconds > TimerInfo.MaximumSecondsToLive) thisTimer.Stop(); 
    } 

    void Work_Tick(object sender, EventArgs e) 
    { 
     //Do work specifically for this timer 
    } 
0

Io generalmente parlando, perché lei non ha citato quale timer, ma tutti hanno le zecche ... quindi:

Avrete bisogno di un contatore della classe come

int count; 

che si inizializza in l'inizio del vostro timer, e avrete bisogno di un dateTime come

DateTime start; 

che si inizializza in t egli inizio del temporizzatore:

start = DateTime.Now; 

e nel metodo tick farai:

if(count++ == 10 || (DateTime.Now - start).TotalSeconds > 2) 
    timer.stop() 

ecco un esempio completo

public partial class meClass : Form 
{ 
    private System.Windows.Forms.Timer t; 
    private int count; 
    private DateTime start; 

    public meClass() 
    { 
    t = new Timer(); 
    t.Interval = 50; 
    t.Tick += new EventHandler(t_Tick); 
    count = 0; 
    start = DateTime.Now; 
    t.Start(); 
    } 

    void t_Tick(object sender, EventArgs e) 
    { 
    if (count++ >= 10 || (DateTime.Now - start).TotalSeconds > 10) 
    { 
     t.Stop(); 
    } 
    // do your stuff 
    } 
} 
4

Quando viene raggiunto intervallo specificato del timer (dopo 3 secondi), verrà chiamato il gestore di eventi timer1_Tick() e sarà possibile interrompere il timer all'interno del gestore eventi.

Timer timer1 = new Timer(); 

timer1.Interval = 3000; 

timer1.Enabled = true; 

timer1.Tick += new System.EventHandler(timer1_Tick); 


void timer1_Tick(object sender, EventArgs e) 
{ 
    timer1.Stop(); // or timer1.Enabled = false; 
} 
+0

Aggiungi spiegazione. – Omar

+0

Quando viene raggiunto l'intervallo specificato dal timer (dopo 3 secondi), verrà richiamato il gestore di eventi timer1_Tick() e sarà possibile interrompere il timer all'interno del gestore eventi. – beastieboy

0

Quando si inizializza il timer, impostare un valore di tag su 0 (zero).

tmrAutoStop.Tag = 0; 

Quindi, a ogni tick aggiungere uno ...

tmrAutoStop.Tag = int.Parse(tmrAutoStop.Tag.ToString()) + 1; 

e verificare se ha raggiunto il numero desiderato:

if (int.Parse(tmrAutoStop.Tag.ToString()) >= 10) 
{ 
    //do timer cleanup 
} 

Utilizzare questa stessa tecnica per alternare il timer evento associato:

if (int.Parse(tmrAutoStop.Tag.ToString()) % 2 == 0) 
{ 
    //do something... 
} 
else 
{ 
    //do something else... 
} 

Per controllare il tempo trascorso (in secondi):

int m = int.Parse(tmrAutoStop.Tag.ToString()) * (1000/tmrAutoStop.Interval); 
Problemi correlati