コード例 #1
0
        /// <summary>
        ///     Processa o comando: DataSaveToFile
        /// </summary>
        /// <param name="request">Comando</param>
        /// <param name="cancellationToken">CancellationToken</param>
        /// <returns>Task</returns>
        public async Task <Unit> Handle(DataSaveToFile request, CancellationToken cancellationToken)
        {
            const int delayToCheck  = 100;
            const int delayToAction = 500;

            if (!request.SaveImmediately)
            {
                Log.Verbose("Application data save requested. Waiting {Milliseconds} milliseconds.",
                            delayToAction);
            }
            else if (_stopwatchDataSaveToFile != null)
            {
                Log.Verbose(
                    "Application data save immediately requested, but there is a task in progress that must be awaited.");
            }
            else
            {
                Log.Verbose("Application data save immediately requested.");
            }

            if (_stopwatchDataSaveToFile != null)
            {
                _stopwatchDataSaveToFile.Restart();

                return(await Task.Run(async() =>
                {
                    while (_stopwatchDataSaveToFile != null)
                    {
                        await Task.Delay(delayToCheck, cancellationToken);
                    }
                    return Unit.Value;
                }, cancellationToken));
            }

            _stopwatchDataSaveToFile = new Stopwatch();
            _stopwatchDataSaveToFile.Start();

            while (!request.SaveImmediately &&
                   _stopwatchDataSaveToFile != null &&
                   _stopwatchDataSaveToFile.ElapsedMilliseconds < delayToAction)
            {
                await Task.Delay(delayToCheck, cancellationToken);
            }

            var data = Program.Data;

            try
            {
                _dataManipulation.SaveToFile(data);

                Log.Debug("Application data saved to: {Path}", _dataManipulation.Path);

                await _messageBus.Publish(new DataSavedToFile(request), cancellationToken);
            }
            catch (Exception exception)
            {
                Log.Error(exception, "Application data cannot save to: {Path}", _dataManipulation.Path);
            }

            _stopwatchDataSaveToFile = null;

            return(Unit.Value);
        }