Example #1
0
        private void MainLoop()
        {
            while (!_stop)
            {
                Task task;
                if (_inProgressCount < _maxConcurrentItems && _coordinator.TryGetTask(out task))
                {
                    Interlocked.Increment(ref _inProgressCount);
                    Send(task);
                }
                else
                {
                    Thread.Sleep(1);
                }

                lock (_connectionLock)
                {
                    if (_reconnectionStopwatch.IsRunning && _reconnectionStopwatch.Elapsed >= ReconnectionDelay)
                    {
                        _reconnectionsCount       += 1;
                        _lastReconnectionTimestamp = DateTime.UtcNow;
                        _connection = _coordinator.CreateConnection(OnPackageArrived, OnConnectionEstablished, OnConnectionClosed);
                        _reconnectionStopwatch.Stop();
                    }
                }

                if (_timeoutCheckStopwatch.Elapsed > EventTimeoutCheckPeriod)
                {
                    var now = DateTime.UtcNow;
                    foreach (var workerItem in _items.Values)
                    {
                        var lastUpdated = new DateTime(Interlocked.Read(ref workerItem.LastUpdatedTicks));
                        if (now - lastUpdated > EventTimeoutDelay)
                        {
                            if (lastUpdated > _lastReconnectionTimestamp)
                            {
                                _coordinator.SignalWorkerFailed(null, string.Format("Worker {0} discovered timed out event which "
                                                                                    + "never got response from server. "
                                                                                    + "Last state update: {1}, last reconnect: {2}, now: {3}.",
                                                                                    _name,
                                                                                    lastUpdated,
                                                                                    _lastReconnectionTimestamp,
                                                                                    now));
                                TryRemoveWorkItem(workerItem);
                            }
                            else
                            {
                                Retry(workerItem);
                            }
                        }
                    }
                    _timeoutCheckStopwatch.Restart();
                }
            }

            _stoppedEvent.Set();
        }