gpt4 book ai didi

c# - Windows 服务中的重叠任务

转载 作者:太空宇宙 更新时间:2023-11-03 14:54:05 25 4
gpt4 key购买 nike

我在执行某些任务的特定时间间隔后触发了此 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# - Windows 服务中的重叠任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50502197/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com