运行方法几次,延迟几秒钟

时间:2015-02-10 08:46:19

标签: c#

在我的控制台应用程序下面的while循环中,调用GenerateRandomBooking()方法5次然后将GenerateRandomBids()延迟2-3秒的最佳方法是什么?

    private static void Main()
    {
        SettingsComponent.LoadSettings();

        while (true)
        {
            try
            {
                    GenerateRandomBooking();
                    GenerateRandomBids();
                    AllocateBids();
                    Thread.Sleep(TimeSpan.FromSeconds(5));
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
    }

2 个答案:

答案 0 :(得分:3)

这样的事情

private static void Main()
{
    SettingsComponent.LoadSettings();

    while (true)
    {
        try
        {
             for(int x=0; x<4 ; x++){
                GenerateRandomBooking(); // Will call 5 times
             }

             Thread.Sleep(2000) // 2 seconds sleep

             GenerateRandomBids();

             AllocateBids();           
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }

    }
}

答案 1 :(得分:2)

使用Thread.Sleep()几乎总是一个坏主意。我相信最好使用计时器:

 System.Timers.Timer timer = new System.Timers.Timer();

 timer.Interval = 2000;
 timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
 timer.Enabled=false;
 void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)    
{
  timer.Enabled=false;
}  

private static void Main()
{
    SettingsComponent.LoadSettings();

    int counter =0;

    while (true)
    {
        try
        {
             GenerateRandomBooking();
             GenerateRandomBids();
             AllocateBids();
             counter ++;            

             if(counter > 4){
               timer.Enabled=true;
               while (timer.Enabled)
                {
                    ///wait time equal to timer interval...
                }
               counter=0;
             }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }

    }
}