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

Dan*_*Dan 1 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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

Sco*_*ain 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 是的,这是服务的定义 (2认同)

Jim*_*hel 5

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

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

程序不是猫.