Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
616 views
in Technique[技术] by (71.8m points)

wait - Better way to constantly run function periodically in C#

I have a C# program that is constantly checking for new additions to an online DB. I have this code to have it check every 10 seconds

    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);
        }
    }

i have error reporting that posts to the DB and if a major error occurs the program shuts down. Outside of the specific errors within my function, is this method secure and efficient?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...