2020-06-29 04:44:35 +02:00
|
|
|
using System;
|
2020-06-28 10:55:27 +02:00
|
|
|
using System.Runtime.CompilerServices;
|
2018-04-24 00:40:36 +02:00
|
|
|
using System.Threading;
|
|
|
|
using System.Threading.Tasks;
|
2020-06-28 10:55:27 +02:00
|
|
|
using BTCPayServer.Logging;
|
2018-04-24 00:40:36 +02:00
|
|
|
using Microsoft.Extensions.Hosting;
|
2020-06-28 10:55:27 +02:00
|
|
|
using Microsoft.Extensions.Logging;
|
2018-04-24 00:40:36 +02:00
|
|
|
|
|
|
|
namespace BTCPayServer.HostedServices
|
|
|
|
{
|
|
|
|
public abstract class BaseAsyncService : IHostedService
|
|
|
|
{
|
2020-07-31 02:35:58 +02:00
|
|
|
private CancellationTokenSource _Cts = new CancellationTokenSource();
|
2018-04-24 00:40:36 +02:00
|
|
|
protected Task[] _Tasks;
|
2021-11-22 09:16:08 +01:00
|
|
|
public readonly Logs Logs;
|
|
|
|
public BaseAsyncService(Logs logs)
|
|
|
|
{
|
|
|
|
Logs = logs;
|
|
|
|
}
|
2018-04-24 00:40:36 +02:00
|
|
|
|
2019-12-26 06:22:36 +01:00
|
|
|
public virtual Task StartAsync(CancellationToken cancellationToken)
|
2018-04-24 00:40:36 +02:00
|
|
|
{
|
2018-04-27 04:52:04 +02:00
|
|
|
_Tasks = InitializeTasks();
|
2018-04-24 00:40:36 +02:00
|
|
|
return Task.CompletedTask;
|
|
|
|
}
|
|
|
|
|
2018-04-27 04:52:04 +02:00
|
|
|
internal abstract Task[] InitializeTasks();
|
2018-04-24 00:40:36 +02:00
|
|
|
|
2018-04-27 04:52:04 +02:00
|
|
|
protected CancellationToken Cancellation
|
2018-04-27 04:44:21 +02:00
|
|
|
{
|
|
|
|
get { return _Cts.Token; }
|
|
|
|
}
|
|
|
|
|
2020-06-28 10:55:27 +02:00
|
|
|
protected async Task CreateLoopTask(Func<Task> act, [CallerMemberName] string caller = null)
|
2018-04-24 00:40:36 +02:00
|
|
|
{
|
|
|
|
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;
|
|
|
|
|
2019-12-26 06:22:36 +01:00
|
|
|
public virtual async Task StopAsync(CancellationToken cancellationToken)
|
2018-04-24 00:40:36 +02:00
|
|
|
{
|
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...");
|
2018-04-24 00:40:36 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|