Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 以指定间隔C连接到数据库(实体框架)的线程计时器_C#_Multithreading_Entity Framework_Timer - Fatal编程技术网

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

C# 以指定间隔C连接到数据库(实体框架)的线程计时器,c#,multithreading,entity-framework,timer,C#,Multithreading,Entity Framework,Timer,我有一个线程timerwindows服务,它连接到数据库,每30秒通过实体框架从指定的表中读取值,并更新其他表值 基于某种条件 对不起,我忘了放置源代码 var timeInterval = config.GetConfigValue(Constants.SpecifiedTimeInterval); // reading from config file var timeDuration = config.GetConfigValue(Constants.SpecifiedTimeElaps

我有一个线程timerwindows服务,它连接到数据库,每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
}

由于我是线程新手,您想知道对该方法的反馈吗?您的一般方法是合理的,但您有一点问题

您正在传递Timeout.Infinite作为最后一个参数,这将使您的计时器成为一次性的。也就是说,它将在触发一次之前等待时间间隔毫秒,然后再也不会触发。如果希望它每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秒进行。

请向我们展示您目前的代码,并详细解释问题,以便我们可以帮助您解决任何问题。您遇到的问题是什么?这里唯一要说的就是你有什么问题在哪里?太棒了。我还有一只猫。