根據這個Stack Overflow discussion,使用Thread.Sleep()
幾乎總是一個壞主意。我將如何重構我的代碼來使用計時器。我試着做以下,使一個開始:用定時器替換代碼而不是線程休眠
namespace Engine
{
internal class Program
{
public static DbConnect DbObject = new DbConnect();
System.Timers.Timer timer = new System.Timers.Timer();
// error here
timer.Interval = 2000;
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
timer.Enabled=false;
}
}
但持續接受cannot resolve symbol
錯誤消息。
namespace Engine
{
internal class Program
{
public static DbConnect DbObject = new DbConnect();
private static void Main()
{
SettingsComponent.LoadSettings();
while (true)
{
try
{
for (int x = 0; x < 4; x++)
{
GenerateRandomBooking();
}
Thread.Sleep(2000);
GenerateRandomBids();
AllocateBids();
Thread.Sleep(2000);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
}
你必須把你的計時器initalization成方法,例如在主要的開始。 – BoeseB 2015-02-10 10:28:12