Example #1
0
        private async Task AcquireLock(CancellationToken cancellationToken)
        {
            //Try and get the lock
            var lockHandle = await _lockManager.TryLockAsync(_lockId, LockDuration, cancellationToken).ConfigureAwait(false);

            if (lockHandle != null)
            {
                var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
                _singletonScope = new SingletonTimerScope(_log, lockHandle, true, LockRefreshInterval, linkedTokenSource);
                _log.Information("Starting Singleton Processor with name {ProcessorName}", _lockId);
                await _channelReceiver.StartAsync(linkedTokenSource.Token).ConfigureAwait(false);

                _lockPollingEnabled = false;

#pragma warning disable 4014
                Task.Run(() =>
                {
                    linkedTokenSource.Token.WaitHandle.WaitOne();
                    //Stop signal received, restart the polling
                    if (!cancellationToken.IsCancellationRequested)
                    {
                        _lockPollingEnabled = true;
                        _log.Information("Singleton Processor with name {ProcessorName} lost its lock", _lockId);
                    }
                }, cancellationToken).ContinueWith(t => linkedTokenSource.Dispose());
#pragma warning restore 4014
            }
            else
            {
                //someone else has locked this instance, start timer to make sure the owner hasn't died
                _lockPollingEnabled = true;
            }
        }
        public async Task StartAsync()
        {
            await _lockManager.InitializeAsync().ConfigureAwait(false);

            if (_timer == null)
            {
                _timer = new Timer
                {
                    AutoReset = true,
                    Interval  = TimerIntervalMs
                };
                _timer.Elapsed += TimerElapsed;
            }
            //Try and get the lock
            var lockHandle = await _lockManager.TryLockAsync(_lockId, TimeSpan.FromSeconds(60), CancellationToken.None).ConfigureAwait(false);

            if (lockHandle != null)
            {
                _singletonScope = new SingletonTimerScope(_log, lockHandle, true);
                _log.Information("Starting Singleton Processor with name {ProcessorName}", _lockId);
                await _channelReceiver.StartAsync().ConfigureAwait(false);
            }
            else
            {
                //someone else has locked this instance, start timer to make sure the owner hasn't died
                _timer.Enabled = true;
            }
        }