-
Notifications
You must be signed in to change notification settings - Fork 21
/
ConsoleHostedService.cs
87 lines (74 loc) · 2.94 KB
/
ConsoleHostedService.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace GenericHostConsoleApp;
internal sealed class ConsoleHostedService : IHostedService
{
private readonly ILogger _logger;
private readonly IHostApplicationLifetime _appLifetime;
private readonly IWeatherService _weatherService;
private Task? _applicationTask;
private int? _exitCode;
public ConsoleHostedService(
ILogger<ConsoleHostedService> logger,
IHostApplicationLifetime appLifetime,
IWeatherService weatherService)
{
_logger = logger;
_appLifetime = appLifetime;
_weatherService = weatherService;
}
public Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogDebug($"Starting with arguments: {string.Join(" ", Environment.GetCommandLineArgs())}");
CancellationTokenSource? _cancellationTokenSource = null;
_appLifetime.ApplicationStarted.Register(() =>
{
_logger.LogDebug("Application has started");
_cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
_applicationTask = Task.Run(async () =>
{
try
{
IReadOnlyList<int> temperatures = await _weatherService.GetFiveDayTemperaturesAsync(_cancellationTokenSource.Token);
for (int i = 0; i < temperatures.Count; i++)
{
_logger.LogInformation($"{DateTime.Today.AddDays(i).DayOfWeek}: {temperatures[i]}");
}
_exitCode = 0;
}
catch (TaskCanceledException)
{
// This means the application is shutting down, so just swallow this exception
}
catch (Exception ex)
{
_logger.LogError(ex, "Unhandled exception!");
_exitCode = 1;
}
finally
{
// Stop the application once the work is done
_appLifetime.StopApplication();
}
});
});
_appLifetime.ApplicationStopping.Register(() =>
{
_logger.LogDebug("Application is stopping");
_cancellationTokenSource?.Cancel();
});
return Task.CompletedTask;
}
public async Task StopAsync(CancellationToken cancellationToken)
{
// Wait for the application logic to fully complete any cleanup tasks.
// Note that this relies on the cancellation token to be properly used in the application.
if (_applicationTask != null)
{
await _applicationTask;
}
_logger.LogDebug($"Exiting with return code: {_exitCode}");
// Exit code may be null if the user cancelled via Ctrl+C/SIGTERM
Environment.ExitCode = _exitCode.GetValueOrDefault(-1);
}
}