Перекрывающиеся задачи в Windows Service - PullRequest
0 голосов
/ 24 мая 2018

У меня эта служба 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 голосов
/ 24 мая 2018

Я думаю, вам нужно просто перевести все поступающие транзакции в ожидание завершения текущей задачи.Но в случае, если время тика для вашего сервисного триггера невелико, пропуски тоже подойдут.Следующие изменения кода могут быть достаточными:

    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 позволят завершить текущую транзакцию, когда ваша служба остановлена, а не частично завершена.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...