【发布时间】:2015-02-10 10:25:39
【问题描述】:
根据这个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());
}
}
}
}
}
【问题讨论】:
-
你必须把你的定时器初始化放到一个方法中,例如在 Main 的开头。
标签: c# multithreading timer