-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSimpleService.cs
More file actions
68 lines (58 loc) · 1.89 KB
/
Copy pathSimpleService.cs
File metadata and controls
68 lines (58 loc) · 1.89 KB
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
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace TestProcessWrapper.LongLived.Application;
public sealed class SimpleService : BackgroundService
{
private ILogger<SimpleService> Logger { get; }
private TimeSpan DelayAfterEachLoop { get; } = TimeSpan.FromMilliseconds(50.0);
public SimpleService(ILogger<SimpleService> logger, IConfiguration configuration)
{
Logger = logger;
const string testArgumentName = "test-argument";
var testArgumentValue = configuration.GetValue<string>(testArgumentName);
Logger.CommandLineArgument($"--{testArgumentName}", testArgumentValue);
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
try
{
RegisterCancellationRequest(stoppingToken);
while (true)
{
await PerformSampleWorkerTask(stoppingToken);
}
}
catch (OperationCanceledException)
{
// This exception is desired, when shutdown is requested. No action is necessary.
Logger.OperationCancelled();
}
catch (Exception e)
{
e.Log(Logger);
}
finally
{
ShutdownService();
}
}
private void RegisterCancellationRequest(CancellationToken stoppingToken)
{
Logger.WaitingForCancellationRequest();
stoppingToken.Register(() => Logger.StopRequestReceived());
stoppingToken.ThrowIfCancellationRequested();
}
private async Task PerformSampleWorkerTask(CancellationToken stoppingToken)
{
await Task.Delay(DelayAfterEachLoop, stoppingToken);
}
private void ShutdownService()
{
Logger.ShuttingDown();
Logger.ShutDownComplete();
}
}