-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQueuedHostedService
58 lines (49 loc) · 1.96 KB
/
QueuedHostedService
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
public class QueuedHostedService : BackgroundService
{
private readonly ILifetimeScope scope;
private readonly IPrincipalProvider provider;
private readonly ILogger<QueuedHostedService> logger;
public QueuedHostedService(
IBackgroundQueue taskQueue,
ILifetimeScope scope,
IPrincipalProvider provider,
ILogger<QueuedHostedService> logger)
{
TaskQueue = taskQueue;
this.scope = scope;
this.provider = provider;
this.logger = logger;
}
public IBackgroundQueue TaskQueue { get; }
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
logger.LogInformation($"Queued Hosted Service is running.{Environment.NewLine}");
await BackgroundProcessing(stoppingToken);
}
private async Task BackgroundProcessing(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
var workItem = await TaskQueue.DequeueAsync(stoppingToken);
try
{
using (var queueScope = this.scope.BeginLifetimeScope(builder => {
builder.RegisterInstance(new StaticPrincipalProvider(provider.GetPrincipal()))
.As<IPrincipalProvider>();
}))
{
await workItem.Work(queueScope, stoppingToken);
}
}
catch (Exception ex)
{
logger.LogError(ex, "Error occurred executing {WorkItem}.", nameof(workItem));
}
}
}
public override async Task StopAsync(CancellationToken stoppingToken)
{
logger.LogInformation("Queued Hosted Service is stopping.");
await base.StopAsync(stoppingToken);
}
}