Exemplo n.º 1
0
        /// <summary>
        /// Главный метод разгребателя очереди на запись в бд.
        /// </summary>
        private async void Consume()
        {
            while (!_cancellationTokenSource.IsCancellationRequested)
            {
                while (_tasksToConsume.TryDequeue(out CurrencyRateOnDate task))
                {
                    try
                    {
                        await _ratesStorage.InsertCurrencyRateAsync(task);
                    }
                    catch (CustomFailException)
                    {
                        _tasksToConsume.Enqueue(task);
                    }
                    catch (DuplicateNameException)
                    {
                    }
                    catch (Exception e)
                    {
                        _logger.Error(e.Message);
                    }
                }

                _taskAddedEvent.WaitOne(5000);
            }
        }
        /// <inheritdoc />
        public void AddCurrencyRatesOnDate(List <CurrencyRateOnDate> currency_rates)
        {
            Task.Factory.StartNew(async() =>
            {
                foreach (var rate in currency_rates)
                {
                    if (_cancellationTokenSource.IsCancellationRequested)
                    {
                        return;
                    }

                    await _ratesStorage.InsertCurrencyRateAsync(rate).ContinueWith(task =>
                    {
                        if (task.Status != TaskStatus.Faulted)
                        {
                            return;
                        }

                        if (task.Exception.InnerExceptions.Any(ex => ex.InnerException is DuplicateNameException))
                        {
                            return;
                        }

                        if (task.Exception.InnerExceptions.Any(ex => ex.InnerException is CustomFailException))
                        {
                            AddCurrencyRatesOnDate(new List <CurrencyRateOnDate> {
                                rate
                            });
                        }
                        else
                        {
                            _logger.Error(task.Exception);
                        }
                    });
                }
            }, _cancellationTokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
        }