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

时间:2013-05-02 22:40:28

标签: c# wait

我有一个C#程序,它不断检查在线数据库的新增功能。我有这个代码让它每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);
        }
    }

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

3 个答案:

答案 0 :(得分:15)

您应该将程序重写为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();
    }
}

答案 1 :(得分:5)

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

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

请参阅Programs are not cats

答案 2 :(得分:3)

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