forked from dotnet/try
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHostedService.cs
More file actions
67 lines (53 loc) · 1.83 KB
/
Copy pathHostedService.cs
File metadata and controls
67 lines (53 loc) · 1.83 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
62
63
64
65
66
67
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Threading;
using System.Threading.Tasks;
using Clockwise;
using Microsoft.Extensions.Hosting;
namespace MLS.Agent
{
public abstract class HostedService : IHostedService, IDisposable
{
private Task _executingTask;
private Budget _budget;
public Task StartAsync(CancellationToken cancellationToken)
{
_budget = new Budget(cancellationToken);
_executingTask = ExecuteAsync(_budget);
// If the task is completed then return it, otherwise it's running
return _executingTask.IsCompleted
? _executingTask
: Task.CompletedTask;
}
public async Task StopAsync(CancellationToken cancellationToken)
{
// Stop called without start
if (_executingTask == null)
{
return;
}
_budget.Cancel();
// Wait until the task completes or the stop token triggers
await Task.WhenAny(
_executingTask,
Task.Delay(-1, cancellationToken));
// Throw if cancellation triggered
cancellationToken.ThrowIfCancellationRequested();
}
protected async Task ExecuteAsync()
{
if (_budget.IsExceeded)
{
return;
}
using (SchedulerContext.Establish(_budget))
{
await Task.Yield();
await ExecuteAsync(_budget);
}
}
protected abstract Task ExecuteAsync(Budget budget);
public void Dispose() => _budget?.Cancel();
}
}