首页 > 解决方案 > 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()
{

}

我希望这种重叠停止。

标签: c#service

解决方案


我认为您需要做的只是让所有即将到来的事务处于忙碌状态,直到当前任务完成。但是,如果您的服务触发器的滴答时间很短,那么跳过也可以。以下代码更改可能就足够了:

    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 中的更改将使当前事务在您的服务停止时完成,而不是部分完成。


推荐阅读