btcpayserver/BTCPayServer/HostedServices/BaseAsyncService.cs

73 lines
2.1 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
2020-06-28 10:55:27 +02:00
using System.IO;
using System.Linq;
2020-06-28 10:55:27 +02:00
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
2020-06-28 10:55:27 +02:00
using BTCPayServer.Logging;
using BTCPayServer.Services;
using BTCPayServer.Services.Rates;
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;
protected Task[] _Tasks;
public virtual Task StartAsync(CancellationToken cancellationToken)
{
_Cts = new CancellationTokenSource();
_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();
await Task.WhenAll(_Tasks);
}
Logs.PayServer.LogInformation($"{this.GetType().Name} successfully exited...");
}
}
}