线程计时器连接到数据库(实体框架)在指定的间隔c#

本文关键字:框架 连接 计时器 数据库 实体 线程 | 更新日期: 2023-09-27 18:17:22

我有一个线程定时器(windows服务)连接到数据库读取值从指定的表(通过实体框架)每30秒和更新其他表的值基于某些条件

对不起,我忘了放源代码

var timeInterval = config.GetConfigValue(Constants.SpecifiedTimeInterval); // reading from config file
var timeDuration = config.GetConfigValue(Constants.SpecifiedTimeElapsed); //reading from config file
TimerCallback cb= new TimerCallback(TimerElapsed);
Timer timerForDatabasePolling = new Timer(cb, null, Convert.ToInt32(timeInterval), System.Threading.Timeout.Infinite);
private static void TimerElapsed(object obj)
{
    //connecting to
}

你想知道对方法的反馈,因为我是新手线程

线程计时器连接到数据库(实体框架)在指定的间隔c#

你的总体方法是合理的,但是你有一个小问题。

你传递Timeout.Infinite作为最后一个参数,这将使你的计时器一次。也就是说,它将在触发一次之前等待timeInterval毫秒,然后它将永远不会再次触发。如果你想让它每30秒触发一次,你可以传递timeInterval作为最后一个参数,但是如果你的处理时间超过30秒,计时器将再次触发,并且你有多个回调并发执行。这通常是件坏事。

你想要做的是将计时器初始化为一次性的,然后让回调重新初始化它。所以你有:

Timer timerForDatabasePolling = new Timer(
    cb, 
    null,
    Convert.ToInt32(timeInterval)
    Timeout.Infinite);

在你的回调中:

private static void TimerElapsed(object obj)
{
    // Do all the stuff you need to do here.
    // When you're done, reset the timer
    timerForDatabasePolling.Change(timeInterval, Timeout.Infinite);
}

确保您不会获得多个并发回调。下一个回调将在前一个回调完成后30秒发生。