Windows 服务中的重叠任务



我让这个窗口服务在执行某些任务的特定时间间隔后触发。但是,当它当前正在执行其任务时,它会再次触发,并且重叠会导致某些数据被覆盖。以下是导致重叠的代码段:

private Timer myTimer;
public Service1()
{
InitializeComponent();
}
private void TimerTick(object sender, ElapsedEventArgs args)
{
ITransaction transaction = new TransactionFactory().GetTransactionFactory("SomeString");

transaction.ExecuteTransaction();
}
protected override void OnStart(string[] args)
{
// Set up a timer to trigger every 10 seconds.  
myTimer = new Timer();
//setting the interval for tick
myTimer.Interval = BaseLevelConfigurationsHandler.GetServiceTimerTickInterval();
//setting the evant handler for time tick
myTimer.Elapsed += new System.Timers.ElapsedEventHandler(TimerTick);
//enable the timer
myTimer.Enabled = true;
}
protected override void OnStop()
{
}

我希望这种重叠停止。

我认为您需要做的只是将所有即将到来的事务放在忙碌的等待中,直到当前任务完成。但是,如果您的服务触发器的时钟周期很短,那么跳过也可以。以下代码更改可能就足够了:

private Timer myTimer;
private static Boolean transactionCompleted;
public Service1()
{
InitializeComponent();
transactionCompleted = true;
}
private void TimerTick(object sender, ElapsedEventArgs args)
{
//check if no transaction is currently executing
if (transactionCompleted)
{
transactionCompleted = false;
ITransaction transaction = new TransactionFactory().GetTransactionFactory("SomeString");

transaction.ExecuteTransaction();
transactionCompleted = true;
}
else
{
//do nothing and wasit for the next tick
}
}
protected override void OnStart(string[] args)
{
// Set up a timer to trigger every 10 seconds.  
myTimer = new Timer();
//setting the interval for tick
myTimer.Interval = BaseLevelConfigurationsHandler.GetServiceTimerTickInterval();
//setting the evant handler for time tick
myTimer.Elapsed += new System.Timers.ElapsedEventHandler(TimerTick);
//enable the timer
myTimer.Enabled = true;
}
protected override void OnStop()
{
//wait until transaction is finished
while (!transactionCompleted)
{
}
transactionCompleted = false;//so that no new transaction can be started
}

注意:OnStop 中的更改将允许当前事务在服务停止时完成,而不是部分完成。

最新更新