sharee.bike-App/TINKLib/ViewModel/PollingUpdateTaskManager.cs

99 lines
2.7 KiB
C#
Raw Normal View History

2022-08-30 15:42:25 +02:00
using System;
2021-05-13 20:03:07 +02:00
using System.Threading.Tasks;
2022-08-30 15:42:25 +02:00
using Serilog;
using TINK.Settings;
2021-05-13 20:03:07 +02:00
namespace TINK.ViewModel
{
2022-09-06 16:08:19 +02:00
/// <summary>
/// Performs a periodic update.
/// </summary>
public class PollingUpdateTaskManager : IPollingUpdateTaskManager
{
/// <summary> Action which performs an update.</summary>
private Action UpdateAction { get; }
/// <summary> Reference on the current polling task</summary>
private PollingUpdateTask UpdateTask { get; set; }
/// <summary>
/// Gets or sets polling parameters.
/// </summary>
private PollingParameters PollingParameters { get; set; }
/// <summary> Prevents an invalid instance to be created. </summary>
private PollingUpdateTaskManager()
{ }
/// <summary>Constructs a update manager object. </summary>
/// <param name="p_oGetChildName">Name of the child class. For logging purposes.</param>
/// <param name="updateAction"></param>
public PollingUpdateTaskManager(
Action updateAction)
{
UpdateAction = updateAction ?? throw new ArgumentException(
$"Can not construct {GetType().Name}- obect. Argument {nameof(updateAction)} must not be null.");
}
/// <summary>
/// Invoked when page is shown.
/// Actuates and awaits the first update process and starts a task wich actuate the subseqent update tasks.
/// </summary>
/// <param name="pollingParameters">Parametes holding polling periode, if null last parameters are used if available.</param>
public async Task StartUpdateAyncPeridically(PollingParameters pollingParameters = null)
{
if (UpdateTask != null)
{
Log.Error($"Call to stop periodic update task missed in context {GetType().Name} at {DateTime.Now}.");
// Call of StopUpdatePeriodically missed.
// Terminate running polling update task before starting a new one
await UpdateTask.Terminate();
}
if (pollingParameters != null)
{
// Backup polling parameter for purposee of restart.
PollingParameters = pollingParameters;
}
if (PollingParameters == null)
{
// No polling parameters avaialable.
Log.Error($"Can not start polling. No parameters available.");
return;
}
if (!PollingParameters.IsActivated)
{
// Automatic supdate is switched off.
Log.ForContext<PollingUpdateTask>().Debug($"Automatic update is off, context {GetType().Name} at {DateTime.Now}.");
return;
}
UpdateTask = new PollingUpdateTask(
UpdateAction,
PollingParameters.Periode);
}
/// <summary>
/// Invoked when pages is closed/ hidden.
/// Stops update process.
/// </summary>
public async Task StopUpdatePeridically()
{
if (UpdateTask == null)
{
// Nothing to do if there is no update task pending.
return;
}
await UpdateTask.Terminate();
UpdateTask = null;
}
}
2021-05-13 20:03:07 +02:00
}