sharee.bike-App/TINKLib/ViewModel/PollingUpdateTask.cs
Anja Müller-Meißner 573fe77e12 Version 3.0.337
2022-08-30 15:42:25 +02:00

128 lines
5.1 KiB
C#

using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Serilog;
using TINK.Repository.Exception;
namespace TINK.ViewModel
{
/// <summary>
/// Object to periodically actuate an action.
/// </summary>
public class PollingUpdateTask
{
/// <summary> Object to control canelling. </summary>
private CancellationTokenSource CanellationTokenSource { get; }
/// <summary> Task to perform update. </summary>
private Task UpdateTask { get; }
/// <summary> Action which performs an update.</summary>
private Action UpdateAction { get; }
/// <summary> Obects which does a periodic update. </summary>
/// <param name="updateAction">Update action to perform.</param>
/// <param name="polling"> Holds whether to poll or not and the periode leght is polling is on. </param>
public PollingUpdateTask(
Action updateAction,
TimeSpan? polling)
{
UpdateAction = updateAction
?? throw new ArgumentException($"Can not construct {GetType().Name}- obect. Argument {nameof(updateAction)} must not be null.");
if (!polling.HasValue)
{
// Automatic update is switched off.
Log.ForContext<PollingUpdateTask>().Debug($"Automatic update is off, context {GetType().Name} at {DateTime.Now}.");
return;
}
var updatePeriodeSet = polling.Value;
CanellationTokenSource = new CancellationTokenSource();
int cycleIndex = 2;
UpdateTask = Task.Run(
async () =>
{
while (!CanellationTokenSource.IsCancellationRequested)
{
await Task.Delay(updatePeriodeSet, CanellationTokenSource.Token);
{
// N. update cycle
Log.ForContext<PollingUpdateTask>().Information($"Actuating {cycleIndex} update cycle, context {GetType().Name} at {DateTime.Now}.");
UpdateAction();
Log.ForContext<PollingUpdateTask>().Debug($"Update cycle {cycleIndex}, context {GetType().Name} finised at {DateTime.Now}.");
cycleIndex = cycleIndex < int.MaxValue ? ++cycleIndex : 0;
}
}
},
CanellationTokenSource.Token);
}
/// <summary>
/// Invoked when pages is closed/ hidden.
/// Stops update process.
/// </summary>
public async Task Terminate()
{
if (UpdateTask == null)
{
// Nothing to do if no task was created.
return;
}
// Cancel update task;
if (CanellationTokenSource == null)
{
throw new Exception($"Can not terminate periodical update task, context {GetType().Name} at {DateTime.Now}. No task running.");
}
Log.Information($"Request to terminate update cycle, context {GetType().Name} at {DateTime.Now}.");
CanellationTokenSource.Cancel();
try
{
await UpdateTask;
}
catch (TaskCanceledException)
{
// Polling update was canceled.
// Nothing to notice/ worry about.
}
catch (Exception exception)
{
// An error occurred updating pin.
var aggregateException = exception as AggregateException;
if (aggregateException == null)
{
// Unexpected exception detected. Exception should alyways be of type AggregateException
Log.Error("An/ several errors occurred on update task. {@Exceptions}.", exception);
}
else
{
if (aggregateException.InnerExceptions.Count == 1
&& aggregateException.InnerExceptions[0].GetType() == typeof(TaskCanceledException))
{
// Polling update was canceled.
// Nothing to notice/ worry about.
}
else if (aggregateException.InnerExceptions.Count() > 0 &&
aggregateException.InnerExceptions.First(x => !x.GetIsConnectFailureException()) == null) // There is no exception which is not of type connect failure.
{
// All exceptions were caused by communication error
Log.Information("An/ several web related connect failure exceptions occurred on update task. {@Exceptions}.", exception);
}
else
{
// All exceptions were caused by communication errors.
Log.Error("An/ several exceptions occurred on update task. {@Exception}.", exception);
}
}
}
}
}
}