-
Notifications
You must be signed in to change notification settings - Fork 0
/
Job.cs
57 lines (54 loc) · 1.46 KB
/
Job.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
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ezThread
{
public class Job
{
public Action A;
private CancellationToken CT;
private CancellationTokenSource source = new CancellationTokenSource();
//times to be executed by an EZTHREAD class instance
public int executions = 1;
public Job(Action a, int exec)
{
A = a;
CT = source.Token;
executions = exec;
}
public Job(Action a)
{
A = a;
CT = source.Token;
}
//Executes the task
public void execute(int times = 1)
{
for (int i = 0; i < times; i++)
{
if (CT.IsCancellationRequested)
{
break;
}
A();
}
}
//Executes the task asynchronously (Doesn't keep the program open)
public async void executeAsync(int times = 1)
{
for (int i = 0; i < times; i++)
{
await Task.Run(A, CT);
}
}
//Cancels the cancellation token then the async task will stop or when the next time a job is ran.
public void cancelExecution()
{
source.Cancel();
source = new CancellationTokenSource();
CT = source.Token;
}
}
}