-
Notifications
You must be signed in to change notification settings - Fork 0
/
BackgroundTask.cs
41 lines (34 loc) · 1.13 KB
/
BackgroundTask.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
namespace Net6_Demo.Workers
{
/// <summary>
/// Handle all background worker here
/// </summary>
public class BackgroundTask : BackgroundService
{
private readonly ILogger<BackgroundTask> _log;
private readonly IEnumerable<IWorker> _worker;
public BackgroundTask(ILogger<BackgroundTask> log, IEnumerable<IWorker> worker)
{
_log = log;
_worker = worker;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_log.LogInformation("{Name} is starting.", GetType().Name);
stoppingToken.Register(() =>
_log.LogInformation("{Name} is stopping.", GetType().Name));
// add all worker
var workers = new List<Task>();
foreach (var x in _worker)
{
workers.Add(x.DoWork(stoppingToken));
}
await Task.WhenAll(workers);
_log.LogInformation("{Name} is stopping.", GetType().Name);
}
}
public interface IWorker
{
Task DoWork(CancellationToken cancellationToken);
}
}