-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWorker.cs
More file actions
61 lines (48 loc) · 1.54 KB
/
Copy pathWorker.cs
File metadata and controls
61 lines (48 loc) · 1.54 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
58
59
60
61
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace AspNetCore.WorkerSample
{
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
private Task _executingTask;
private CancellationTokenSource _cts;
public Worker(ILogger<Worker> logger)
{
_logger = logger;
}
public override Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogWarning("Worker service started.");
_cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
_executingTask = ExecuteAsync(_cts.Token);
return _executingTask.IsCompleted ? _executingTask : Task.CompletedTask;
}
public override Task StopAsync(CancellationToken cancellationToken)
{
if (_executingTask == null)
{
return Task.CompletedTask;
}
_logger.LogWarning("Worker service stopping.");
_cts.Cancel();
Task.WhenAny(_executingTask, Task.Delay(-1, cancellationToken)).ConfigureAwait(true);
cancellationToken.ThrowIfCancellationRequested();
_logger.LogWarning("Worker service stopped.");
return Task.CompletedTask;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
await Task.Delay(1000, stoppingToken);
}
}
}
}