Synchronizing a timer to prevent overlap

后端 未结 6 2212
谎友^
谎友^ 2020-12-08 21:02

I\'m writing a Windows service that runs a variable length activity at intervals (a database scan and update). I need this task to run frequently, but the code to handle isn

6条回答
  •  旧时难觅i
    2020-12-08 21:55

    instead of locking (which could cause all of your timed scans to wait and eventually stack up). You could start the scan/update in a thread and then just do a check to see if the thread is still alive.

    Thread updateDBThread = new Thread(MyUpdateMethod);
    

    ...

    private void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        if(!updateDBThread.IsAlive)
            updateDBThread.Start();
    }
    

提交回复
热议问题