-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathLoopHostedService.cs
58 lines (48 loc) · 2.27 KB
/
LoopHostedService.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
55
56
57
58
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Cysharp.Threading;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace LoopHostingApp
{
class LoopHostedService : IHostedService
{
private readonly ILogicLooperPool _looperPool;
private readonly ILogger _logger;
public LoopHostedService(ILogicLooperPool looperPool, ILogger<LoopHostedService> logger)
{
_looperPool = looperPool ?? throw new ArgumentNullException(nameof(looperPool));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public Task StartAsync(CancellationToken cancellationToken)
{
// Example: Register update action immediately.
_ = _looperPool.RegisterActionAsync((in LogicLooperActionContext ctx) =>
{
if (ctx.CancellationToken.IsCancellationRequested)
{
// If LooperPool begins shutting down, IsCancellationRequested will be `true`.
_logger.LogInformation("LoopHostedService will be shutdown soon. The registered action is shutting down gracefully.");
return false;
}
return true;
});
// Example: Create a new world of life-game and register it into the loop.
// - See also: LoopHostingApp/Pages/Index.cshtml.cs
LifeGameLoop.CreateNew(_looperPool, _logger);
_logger.LogInformation($"LoopHostedService is started. (Loopers={_looperPool.Loopers.Count}; TargetFrameRate={_looperPool.Loopers[0].TargetFrameRate:0}fps)");
return Task.CompletedTask;
}
public async Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("LoopHostedService is shutting down. Waiting for loops.");
// Shutdown gracefully the LooperPool after 5 seconds.
await _looperPool.ShutdownAsync(TimeSpan.FromSeconds(5));
// Count remained actions in the LooperPool.
var remainedActions = _looperPool.Loopers.Sum(x => x.ApproximatelyRunningActions);
_logger.LogInformation($"{remainedActions} actions are remained in loop.");
}
}
}