-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMyServiceA.cs
49 lines (38 loc) · 2.03 KB
/
MyServiceA.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
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace DotNetCoreGenericHostSample
{
public class MyServiceA : BackgroundService
{
public MyServiceA(ILoggerFactory loggerFactory)
{
Logger = loggerFactory.CreateLogger<MyServiceA>();
Logger.LogInformation("{0} : MyServiceA constructed.", DateTime.Now.ToString());
}
public ILogger Logger { get; }
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
Logger.LogInformation("{0} : MyServiceA background task is starting.", DateTime.Now.ToString());
stoppingToken.Register(() => Logger.LogInformation("{0} : MyServiceA is stopping.", DateTime.Now.ToString()));
// Add a delay before first run to allow time for any database to first be created etc.
//await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken);
// Perform any required preparation here...
while (!stoppingToken.IsCancellationRequested)
{
Logger.LogInformation("{0} : MyServiceA is doing background work.", DateTime.Now.ToString());
// When this is cancelled, an Exception is raised preventing any clean-up code from running.
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
// Allows the clean-up code below to run by swallowing the exception raised by cancelling the Delay
//await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken).ContinueWith(task => { });
}
Logger.LogInformation("{0} : MyServiceA background task is stopping.", DateTime.Now.ToString());
// Perform any required clean-up here...
// Close database connections etc...
await Task.Delay(TimeSpan.FromMilliseconds(500));
Logger.LogInformation("{0} : MyServiceA background task clean-up completed.", DateTime.Now.ToString());
}
}
}