如何使用c#在循环中每10分钟运行一次函数?

时间:2012-03-14 04:02:53

标签: c# .net winforms timer

我有一个循环,根据某些条件连续运行一个函数。 现在,我想在循环内每10分钟调用一次该函数。 我正在使用Visual Studio 2005.我的代码是:

    while (boolValue == false)
    {
         Application.DoEvents();
         StartAction();    //i want to call this function for every 10 minutes only
    }

我正在使用System.Timers,但它没有调用该函数。我不知道出了什么问题。

我的代码是:

   public static System.Timers.Timer aTimer;
   while (boolValue == false)
   {
        aTimer = new System.Timers.Timer(50000);
        aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        aTimer.AutoReset = false;
        aTimer.Enabled = true;
   }

   private static void OnTimedEvent(object source, ElapsedEventArgs e)
   {
        Application.DoEvents();
        StartAction();
   }

1 个答案:

答案 0 :(得分:6)

为什么不使用timer。让它每十分钟触发一次。

更具体的版本中的example实际上是一个很好的例子

<强>更新

在您更新的代码中,我会将其更改为:

public static System.Timers.Timer aTimer;
...
aTimer = new System.Timers.Timer(50000);
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.AutoReset = false; //This should be true if you want it actually looping
aTimer.Enabled = true;

我没有理由有一个while循环。我的猜测是while循环根本没有触发。此外,您应该将AutoReset设置为true,这样就可以连续运行。