-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathPublishWorker.cs
54 lines (43 loc) · 1.55 KB
/
PublishWorker.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
using System.Diagnostics.CodeAnalysis;
using TinyIpc.Messaging;
namespace GenericHost;
[SuppressMessage("Performance", "CA1812:Avoid uninstantiated internal classes", Justification = "DI")]
internal sealed partial class PublishWorker(ITinyMessageBus tinyMessageBus, LoremIpsum loremIpsum, ILogger<PublishWorker> logger)
: BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
// Say hello
await PublishMessage("hello", stoppingToken);
try
{
while (!stoppingToken.IsCancellationRequested)
{
// Random delay to make it interesting, comment out the delay to make really make it go
await Task.Delay(Random.Shared.Next(1_000, 3_000), stoppingToken);
// Say nonsense
await PublishMessage(loremIpsum.GetSentence(), stoppingToken);
}
}
finally
{
// Say goodbye, not using stoppingToken or the message won't be sent
await PublishMessage("goodbye", default);
LogCount(tinyMessageBus.MessagesPublished);
}
}
private Task PublishMessage(string sentence, CancellationToken cancellationToken)
{
var message = new WorkerMessage
{
ProcessId = Environment.ProcessId,
Sentence = sentence
};
LogMessage(message.ProcessId, message.Sentence);
return tinyMessageBus.PublishAsync(message.Serialize(), cancellationToken);
}
[LoggerMessage(1, LogLevel.Information, "Published message as {pid}: {sentence}")]
private partial void LogMessage(int pid, string sentence);
[LoggerMessage(2, LogLevel.Information, "Published {count} messages")]
private partial void LogCount(long count);
}