-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMessageEventsBackgroundService.cs
More file actions
57 lines (48 loc) · 1.81 KB
/
MessageEventsBackgroundService.cs
File metadata and controls
57 lines (48 loc) · 1.81 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
using System;
using System.Threading;
using System.Threading.Tasks;
using MassTransit;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace BackgroundTasks
{
public class MessageEventsBackgroundService : BackgroundService
{
private readonly IBusControl _busControl;
private readonly ILogger<MessageEventsBackgroundService> _logger;
public MessageEventsBackgroundService(IBusControl busControl, ILogger<MessageEventsBackgroundService> logger)
{
_busControl = busControl;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
try
{
_logger.LogInformation("Starting the bus...");
await _busControl.StartAsync(stoppingToken);
_logger.LogInformation($"Starting service {nameof(MessageEventsBackgroundService)}");
while (!stoppingToken.IsCancellationRequested)
{
// Keeps the service alive until it is cancelled.
await _busControl.Publish(new SampleMessage { Message = "Hello World"}, stoppingToken);
Thread.Sleep(10_000);
}
}
catch (Exception e)
{
_logger.LogError($"Error in {nameof(MessageEventsBackgroundService)}. Exception {e}");
}
finally
{
_logger.LogInformation("Stopping the bus...");
await _busControl.StopAsync(stoppingToken);
}
}
public override Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Stopping the bus...");
return _busControl.StopAsync(cancellationToken);
}
}
}