Example #1
0
        public Task MonitoredPropertiesProcessorAsync()
        {
            DateTime nextSendTime             = DateTime.UtcNow + TimeSpan.FromSeconds(_defaultSendIntervalSeconds);
            double   millisecondsTillNextSend = nextSendTime.Subtract(DateTime.UtcNow).TotalMilliseconds;

            while (!_shutdownToken.IsCancellationRequested)
            {
                try
                {
                    // sanity check the send interval, compute the timeout and get the next monitored item message
                    if (_defaultSendIntervalSeconds > 0)
                    {
                        millisecondsTillNextSend = nextSendTime.Subtract(DateTime.UtcNow).TotalMilliseconds;
                        if (millisecondsTillNextSend < 0)
                        {
                            // do not wait if we missed the send interval
                            millisecondsTillNextSend = 0;
                        }
                    }
                    else
                    {
                        // if we are in shutdown do not wait, else wait infinite if send interval is not set
                        millisecondsTillNextSend = _shutdownToken.IsCancellationRequested ? 0 : Timeout.Infinite;
                    }

                    var gotItem = _monitoredPropertiesDataQueue.TryTake(out var messageData, (int)millisecondsTillNextSend, _shutdownToken);

                    if (!gotItem || messageData == null)
                    {
                        continue;
                    }
                    _hubClient.SendPropertyAsync(messageData, _shutdownToken).GetAwaiter().GetResult();

                    SentProperties++;
                }
                catch (Exception e)
                {
                    _logger.Error(e, "Error while processing monitored properties.");
                }
            }

            return(Task.CompletedTask);
        }