1

我有一个 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);
        }
    }

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

4

3 回答 3

15

You should rewrite your program as a windows service, that way you do not need to rely on a user to be logged for your program to run.

If you do go with the service route, I would swap out the infinite loop for a timer.

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();
    }
}
于 2013-05-02T22:44:56.780 回答
5

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

您可以使用任务计划程序 GUI 或 schtasks 命令行工具。

请参阅程序不是猫

于 2013-05-02T22:49:57.487 回答
3

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

于 2013-05-02T22:56:12.863 回答