在C#中定期不断运行函数的更好方法

我有一个C#程序,它不断检查在线数据库的新增function。 我有这个代码让它每10秒检查一次

static void Main(string[] args) { boolean run = true; while (run) { DBConnect Db = new DBConnect(); // do amazing awesome mind blowing cool stuff Db.closeConnection(); // wait for 10 seconds int wait = 10 * 1000; System.Threading.Thread.Sleep(wait); } } 

我有错误报告,发布到数据库,如果发生重大错误,程序关闭。 在我的函数中的特定错误之外,这种方法安全有效吗?

您应该将程序重写为Windows服务,这样您就不需要依赖用户来记录您的程序运行。

如果你确实使用了服务路由,我会将无限循环换成计时器。

 public partial class Service1 : ServiceBase { public Service1() { InitializeComponent(); int wait = 10 * 1000; timer = new Timer(wait); timer.Elapsed += timer_Elapsed; // We don't want the timer to start ticking again till we tell it to. timer.AutoReset = false; } private System.Timers.Timer timer; protected override void OnStart(string[] args) { timer.Start(); } void timer_Elapsed(object sender, ElapsedEventArgs e) { try { DBConnect Db = new DBConnect()) try { // do amazing awesome mind blowing cool stuff } finally { Db.closeConnection(); //We put this in a finally block so it will still happen, even if an exception is thrown. } timer.Start(); } catch(SomeNonCriticalException ex) { MyExecptionLogger.Log(ex, Level.Waring); //Log the exception so you know what went wrong timer.Start(); //Start the timer for the next loop } catch(Exception ex) { MyExecptionLogger.Log(ex, Level.Critical); //Log the exception so you know what went wrong this.Stop(); //Stop the service } } protected override void OnStop() { timer.Stop(); } } 

将其写为控制台程序,无需等待,并设置计划任务以定期运行它。 你想每10秒运行一次吗? 每一分钟? 只需更改计划任务即可。

您可以使用Task Scheduler GUI或schtasks命令行工具。

看程序不是猫 。

我会设置一个Windows服务并使用SqlDependency http://msdn.microsoft.com/en-CA/library/a52dhwx7(v=vs.80).aspx 。 这样,当数据库中发生更改(您指定)时,它将触发您指定的OnChange事件,以执行您需要执行的任何操作。 请参阅链接以了解实施细节。