c# - Windows 服务中的重叠任务
问题描述
我在执行某些任务的特定时间间隔后触发了此 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 中的更改将使当前事务在您的服务停止时完成,而不是部分完成。
推荐阅读
- c - fscanf 导致分段错误
- python - 如何访问类并获取可用操作的 dir()?
- git - Git 错误“无法将对象迁移到永久存储”从 bitbucket 推送到 Azure webapp
- java - 如何修复 getSource() 方法以在 actionPerformed 类中编辑 JButton 文本?
- speech-recognition - 有没有办法使用 HTK 获得单音素概率?
- amazon-web-services - 如何修复 DynamoDB JS API 阻塞和超时我的 Lambda 函数?
- java - 修改后的 N 皇后与放置的皇后
- react-native - 如何使 ScrollView 仅在 React Native 中的子大小较大时滚动
- aws-glue - JSON ISO 8601 时间字符串到时间格式 AWS-Glue
- javascript - 在 Sequelize 中创建此 SQL