Windows服务中的重叠任务

时间:2018-05-24 06:14:50

标签: c# service

我在执行某项任务的特定时间间隔后触发了此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()
{

}

我希望这种重叠停止。

1 个答案:

答案 0 :(得分:1)

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

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