btcpayserver/BTCPayServer/HostedServices/BaseAsyncService.cs

72 lines
2.1 KiB
C#
Raw Normal View History

2020-06-29 04:44:35 +02:00
using System;
2020-06-28 10:55:27 +02:00
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
2020-06-28 10:55:27 +02:00
using BTCPayServer.Logging;
using Microsoft.Extensions.Hosting;
2020-06-28 10:55:27 +02:00
using Microsoft.Extensions.Logging;
namespace BTCPayServer.HostedServices
{
public abstract class BaseAsyncService : IHostedService
{
private CancellationTokenSource _Cts = new CancellationTokenSource();
protected Task[] _Tasks;
2021-11-22 09:16:08 +01:00
public readonly Logs Logs;
public BaseAsyncService(Logs logs)
{
Logs = logs;
}
public virtual Task StartAsync(CancellationToken cancellationToken)
{
_Tasks = InitializeTasks();
return Task.CompletedTask;
}
internal abstract Task[] InitializeTasks();
protected CancellationToken Cancellation
{
get { return _Cts.Token; }
}
2020-06-28 10:55:27 +02:00
protected async Task CreateLoopTask(Func<Task> act, [CallerMemberName] string caller = null)
{
await new SynchronizationContextRemover();
while (!_Cts.IsCancellationRequested)
{
try
{
await act();
}
catch (OperationCanceledException) when (_Cts.IsCancellationRequested)
{
}
catch (Exception ex)
{
Logs.PayServer.LogWarning(ex, caller + " failed");
try
{
await Task.Delay(TimeSpan.FromMinutes(1), _Cts.Token);
}
catch (OperationCanceledException) when (_Cts.IsCancellationRequested) { }
}
}
}
2020-06-24 03:34:09 +02:00
public CancellationToken CancellationToken => _Cts.Token;
public virtual async Task StopAsync(CancellationToken cancellationToken)
{
2019-10-19 07:12:43 +02:00
if (_Cts != null)
{
_Cts.Cancel();
2021-10-12 10:39:48 +02:00
if (_Tasks != null)
await Task.WhenAll(_Tasks);
2019-10-19 07:12:43 +02:00
}
Logs.PayServer.LogInformation($"{this.GetType().Name} successfully exited...");
}
}
}