简体   繁体   中英

Create a .NET Threading.Timer with a period Timeout.Infinite

What I want, a windows service that performs a function with a interval, without opening multiple threads.

What I did, using a Threading.Timer I created the following code:

protected override void OnStart(string[] args) {
  System.Threading.Timer timer1 = new System.Threading.Timer(new TimerCallback(Risk), null, 60000, Timeout.Infinite);
}
public void Risk(object state) {
  try{
    //long operation
  }
  catch(ex){
  }
  finally{
    timer1.Change(1000, Timeout.Infinite);
  }
}

My problem, it looks like this code is opening multiple threads. Is this possible? Where did I go wrong? This a good way to get what I want?

UPDATE (using System.Timers.Timer):

 protected override void OnStart(string[] args) {
    System.Timers.Timer aTimer;
    aTimer = new System.Timers.Timer(60000);
    aTimer.Elapsed += Risk;
    aTimer.AutoReset = true;
    aTimer.Enabled = true;
 }

 private void Risk(Object source, ElapsedEventArgs e) {
    aTimer.Enabled = false;
    try{}
    catch(ex){}
    finally{
      aTimer.Interval = 1000;
      aTimer.Enabled = true;
    }
 }

Multiple timer ticks can run concurrently. The timer class does not wait for ticks to complete. (I think it should have such a feature because it's almost always what you want.)

An easy fix is to run an loop with Task.Delay :

while (!cancel) {
 DoStuff();
 await Task.Delay(...);
}

And you kick that off with Task.Run(() => { AsyncCodeHere(); }); .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM