-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWindowsBackgroundService.cs
More file actions
42 lines (35 loc) · 1.33 KB
/
WindowsBackgroundService.cs
File metadata and controls
42 lines (35 loc) · 1.33 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
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace MQTTOperationsService
{
public sealed class WindowsBackgroundService : BackgroundService
{
private readonly ILogger<WindowsBackgroundService> _logger;
private readonly IMQTTWorker _mqttWorker;
public WindowsBackgroundService(IMQTTWorker mqttWorker,
ILogger<WindowsBackgroundService> logger)
{
_mqttWorker = mqttWorker;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("Starting MQTT Operations Service at: {time}", DateTimeOffset.Now);
await _mqttWorker.Initialise(stoppingToken);
WhenCancelled(stoppingToken).Wait(stoppingToken);
_logger.LogInformation("Service stopped.");
}
}
private static Task WhenCancelled(CancellationToken cancellationToken)
{
var tcs = new TaskCompletionSource<bool>();
cancellationToken.Register(s => ((TaskCompletionSource<bool>)s).SetResult(true), tcs);
return tcs.Task;
}
}
}