Skip to content

Commit 21484d6

Browse files
Improved the IHostedService background task (GracePeriodManagerService) in the Ordering microservice to use the new BackgroundService abstract base class from .NET Core 2.1 (.NET Standard 2.1). We're currently using that class code embeded in eShopOnContainers project until .NET Core 2.1 is released with this new class.
The new class BackgroundService is compatible with the current IHostedService interface in .NET Core 2.0. I removed the similar but nont-tested HostedService base class (it was not official from the .NET team) that we were previously using.
1 parent 39d5ebc commit 21484d6

3 files changed

Lines changed: 97 additions & 60 deletions

File tree

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
using System;
2+
using System.Threading;
3+
using System.Threading.Tasks;
4+
5+
using Microsoft.Extensions.Hosting;
6+
7+
namespace Ordering.API.Infrastructure.HostedServices
8+
{
9+
// Copyright (c) .NET Foundation. All rights reserved.
10+
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
11+
12+
/// <summary>
13+
/// Base class for implementing a long running <see cref="IHostedService"/>.
14+
/// IMPORTANT: This base class is implemented in .NET Core 2.1 - Since this microservice is still in .NET Core 2.0, we're using the class within the project
15+
/// When .NET Core 2.1 is released, this class should be removed and you should use the use implemented by the framework
16+
/// https://github.com/aspnet/Hosting/blob/712c992ca827576c05923e6a134ca0bec87af4df/src/Microsoft.Extensions.Hosting.Abstractions/BackgroundService.cs
17+
///
18+
/// </summary>
19+
public abstract class BackgroundService : IHostedService, IDisposable
20+
{
21+
private Task _executingTask;
22+
private readonly CancellationTokenSource _stoppingCts = new CancellationTokenSource();
23+
24+
/// <summary>
25+
/// This method is called when the <see cref="IHostedService"/> starts. The implementation should return a task that represents
26+
/// the lifetime of the long running operation(s) being performed.
27+
/// </summary>
28+
/// <param name="stoppingToken">Triggered when <see cref="IHostedService.StopAsync(CancellationToken)"/> is called.</param>
29+
/// <returns>A <see cref="Task"/> that represents the long running operations.</returns>
30+
protected abstract Task ExecuteAsync(CancellationToken stoppingToken);
31+
32+
/// <summary>
33+
/// Triggered when the application host is ready to start the service.
34+
/// </summary>
35+
/// <param name="cancellationToken">Indicates that the start process has been aborted.</param>
36+
public virtual Task StartAsync(CancellationToken cancellationToken)
37+
{
38+
// Store the task we're executing
39+
_executingTask = ExecuteAsync(_stoppingCts.Token);
40+
41+
// If the task is completed then return it, this will bubble cancellation and failure to the caller
42+
if (_executingTask.IsCompleted)
43+
{
44+
return _executingTask;
45+
}
46+
47+
// Otherwise it's running
48+
return Task.CompletedTask;
49+
}
50+
51+
/// <summary>
52+
/// Triggered when the application host is performing a graceful shutdown.
53+
/// </summary>
54+
/// <param name="cancellationToken">Indicates that the shutdown process should no longer be graceful.</param>
55+
public virtual async Task StopAsync(CancellationToken cancellationToken)
56+
{
57+
// Stop called without start
58+
if (_executingTask == null)
59+
{
60+
return;
61+
}
62+
63+
try
64+
{
65+
// Signal cancellation to the executing method
66+
_stoppingCts.Cancel();
67+
}
68+
finally
69+
{
70+
// Wait until the task completes or the stop token triggers
71+
await Task.WhenAny(_executingTask, Task.Delay(Timeout.Infinite, cancellationToken));
72+
}
73+
74+
}
75+
76+
public virtual void Dispose()
77+
{
78+
_stoppingCts.Cancel();
79+
}
80+
}
81+
82+
83+
}

src/Services/Ordering/Ordering.API/Infrastructure/HostedServices/GracePeriodManagerService.cs

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,7 @@
1212
using System.Threading;
1313
using System.Threading.Tasks;
1414

15-
public class GracePeriodManagerService
16-
: HostedService
15+
public class GracePeriodManagerService : BackgroundService
1716
{
1817
private readonly OrderingSettings _settings;
1918
private readonly ILogger<GracePeriodManagerService> _logger;
@@ -25,26 +24,28 @@ public GracePeriodManagerService(IOptions<OrderingSettings> settings,
2524
{
2625
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
2726
_eventBus = eventBus ?? throw new ArgumentNullException(nameof(eventBus));
28-
2927
_settings = settings?.Value ?? throw new ArgumentNullException(nameof(settings));
3028
}
3129

32-
protected override async Task ExecuteAsync(CancellationToken cancellationToken)
30+
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
3331
{
34-
while (true)
32+
_logger.LogDebug($"GracePeriod background task is starting.");
33+
34+
stoppingToken.Register(() => _logger.LogDebug($"#1 GracePeriod background task is stopping."));
35+
36+
while (!stoppingToken.IsCancellationRequested)
3537
{
36-
if (cancellationToken.IsCancellationRequested)
37-
{
38-
break;
39-
}
38+
_logger.LogDebug($"GracePeriod background task is doing background work.");
4039

4140
CheckConfirmedGracePeriodOrders();
4241

43-
await Task.Delay(_settings.CheckUpdateTime, cancellationToken);
42+
await Task.Delay(_settings.CheckUpdateTime, stoppingToken);
4443

4544
continue;
4645
}
4746

47+
_logger.LogDebug($"GracePeriod background task is stopping.");
48+
4849
await Task.CompletedTask;
4950
}
5051

@@ -54,10 +55,11 @@ private void CheckConfirmedGracePeriodOrders()
5455

5556
var orderIds = GetConfirmedGracePeriodOrders();
5657

58+
_logger.LogDebug($"GracePeriod sent a .");
5759
foreach (var orderId in orderIds)
5860
{
59-
var confirmGracePeriodEvent = new GracePeriodConfirmedIntegrationEvent(orderId);
60-
_eventBus.Publish(confirmGracePeriodEvent);
61+
var gracePeriodConfirmedEvent = new GracePeriodConfirmedIntegrationEvent(orderId);
62+
_eventBus.Publish(gracePeriodConfirmedEvent);
6163
}
6264
}
6365

src/Services/Ordering/Ordering.API/Infrastructure/HostedServices/HostedService.cs

Lines changed: 0 additions & 48 deletions
This file was deleted.

0 commit comments

Comments
 (0)