-
Notifications
You must be signed in to change notification settings - Fork 0
/
TaskProcessorService.cs
69 lines (56 loc) · 2.74 KB
/
TaskProcessorService.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
59
60
61
62
63
64
65
66
67
68
69
using System.Collections.Concurrent;
namespace hello_api;
public class TaskProcessorService : BackgroundService
{
private readonly IBackgroundTaskQueue _queue;
private readonly ILogger<MyController> _logger;
private List<Task<WorkItem>> workItemsTasksInProgress = new();
private List<WorkItem> workItemsDone = new();
public TaskProcessorService(IBackgroundTaskQueue queue, ILogger<MyController> logger)
{
_queue = queue;
_logger = logger;
}
public override Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Starting the background service");
return base.StartAsync(cancellationToken);
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
do
{
// Grab a list of the items in progress but just as generic Task not as Task<WorkItem>
var itemsInProgress = workItemsTasksInProgress.Cast<Task>();
// now add add the dequeuing task to this list
var dequeueATaskOfWorkitemTask = _queue.DequeueAsync();
var tasksToWaitFor = itemsInProgress.Append(dequeueATaskOfWorkitemTask).ToArray();
// wait for for either a dequeue completion event (new item arrived) or
// one of te workItem tasks finishing.
var someFinishedTask = await Task.WhenAny(tasksToWaitFor);
/* TODO how to handle cancellations */
// If it's a new workitem task add it to the list of `in progress owrkitem tasks`.
if (someFinishedTask == dequeueATaskOfWorkitemTask)
{
// Grab the task created by the CreateLongRunningTask as the result of the dequeue operation
var workItemInProgress = dequeueATaskOfWorkitemTask.Result;
workItemsTasksInProgress.Add(workItemInProgress);
}
else // it's a completed work item task so deal with it's completion.
{
// remove from the tasksInProgress
var theFinishedWorkItemTask = (Task<WorkItem>)someFinishedTask;
workItemsTasksInProgress.Remove(theFinishedWorkItemTask);
// add the finished workItem to the done list
var theFinishedWorkItem = theFinishedWorkItemTask.Result;
workItemsDone.Add(theFinishedWorkItem);
Console.WriteLine($"Summary from finished workItem {theFinishedWorkItem.Summary}");
}
} while (true);
}
public override Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Ending the background service");
return base.StopAsync(cancellationToken);
}
}