[英]Run method several times and delay one by a few seconds
What would be the best way of calling the GenerateRandomBooking()
method 5 times and then delaying the GenerateRandomBids()
by 2-3 seconds in the while loop below of my console application? 在控制台应用程序下面的while循环中,调用5次
GenerateRandomBooking()
方法然后将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());
}
}
}
What about something like this 那这样的事呢
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());
}
}
}
using Thread.Sleep()
is almost always a bad idea. 使用
Thread.Sleep()
几乎总是一个坏主意。 I believe it is better to use a timer: 我相信最好使用计时器:
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());
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.