forked from kartikvaidya13/CNCJobQueueManager
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJobQueueManager.cs
More file actions
89 lines (77 loc) · 3.1 KB
/
Copy pathJobQueueManager.cs
File metadata and controls
89 lines (77 loc) · 3.1 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace CNCJobQueueManager
{
public class JobQueueManager
{
// Thread-safe queue to store CNC Jobs
private ConcurrentQueue<CNCJob> jobQueue = new ConcurrentQueue<CNCJob>();
// Token source to manage cancellation of job processing
private CancellationTokenSource cts = new CancellationTokenSource();
// Event to notify subscribers when job is updated
public event Action<CNCJob> JobUpdated;
/// <summary>
/// Adds a job to the job queue and notifies subscribers that the job has been added
/// </summary>
/// <param name="job"></param>
public void EnqueueJob(CNCJob job)
{
// Enqueues the job to the job queue
jobQueue.Enqueue(job);
// Notifies subscribers that the job has been added
JobUpdated?.Invoke(job);
}
/// <summary>
/// Processes jobs asynchronously until cancellation is requested and notifies subscribers of job status updates.
/// </summary>
/// <returns>A task representing the asynchronous operation.</returns>
public async Task ProcessJobsAsync()
{
// Continue processing jobs until cancellation is requested
while (!cts.IsCancellationRequested)
{
// Try to dequeue a job from the job queue
if (jobQueue.TryDequeue(out CNCJob job))
{
// Update job status to InProgress and notify subscribers
job.Status = JobStatus.InProgress;
// if job is updated, notify subscribers
JobUpdated?.Invoke(job);
// Simulate job processing
try
{
// Simulate job processing by delaying for 2 seconds
await Task.Delay(2000, cts.Token);
// Update job status to Completed and notify subscribers
job.Status = JobStatus.Completed;
}
catch (TaskCanceledException)
{
// If the task is cancelled, update job status to Failed and notify subscribers
job.Status = JobStatus.Failed; // updates status to failed
}
// Notify subscribers that the job has been updated
JobUpdated?.Invoke(job);
}
else
{
// Wait for a short period before checking the queue again for new jobs
await Task.Delay(500);
}
}
}
/// <summary>
/// Cancels job processing by requesting cancellation of the token source
/// </summary>
public void StopProcessing()
{
// request cancellation of the token source
cts.Cancel();
}
}
}