首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >方法多次运行,并将一个方法延迟几秒钟。

方法多次运行,并将一个方法延迟几秒钟。
EN

Stack Overflow用户
提问于 2015-02-10 08:46:18
回答 2查看 97关注 0票数 0

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

代码语言:javascript
复制
    private static void Main()
    {
        SettingsComponent.LoadSettings();

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

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-02-10 08:52:35

像这样的东西怎么样

代码语言:javascript
复制
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());
        }

    }
}
票数 3
EN

Stack Overflow用户

发布于 2015-02-10 09:05:21

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

代码语言:javascript
复制
 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());
        }

    }
}  
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28427347

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档