C# - Continuous task example
1 minute read
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
90
91
92
93
94
95
96
97
98
99
100
public interface IContinueTask
{
string TaskName { get ; }
TimeSpan Interval { get ; }
IObservable < TimeSpan > ObservableIntervalChange { get ; }
void Action () ;
}
public class ContinuousTaskItem
{
private CancellationTokenSource m _ cancelTokenSource = new CancellationTokenSource () ;
private IContinueTask m _ task ;
public ContinuousTaskItem ( IContinueTask task )
{
m _ task = task ;
}
public bool Cancel ()
{
m _ cancelTokenSource . Cancel () ;
return true ;
}
public Task Create ()
{
return Task . Factory . StartNew (
() =>
{
while ( true )
{
if ( m _ cancelTokenSource . Token . WaitHandle . WaitOne ( m _ task . Interval ))
break ;
m _ task . Action () ;
}
} , m _ cancelTokenSource . Token , TaskCreationOptions . LongRunning , TaskScheduler . Default ) ;
}
}
public class ContinuousTaskManager
{
private Dictionary < string , ContinuousTaskItem > m _ taskList = new Dictionary < string , ContinuousTaskItem > () ;
public ContinuousTaskManager ()
{
}
public bool AddContinueTask ( IContinueTask task )
{
lock ( m _ taskList )
{
if ( m _ taskList . Keys . FirstOrDefault ( x => x == task . TaskName ) == null )
{
var ob = task . ObservableIntervalChange . Subscribe (
interval =>
{
lock ( m _ taskList )
{
// delete task
ContinuousTaskItem taskItem = null ;
if ( m _ taskList . TryGetValue ( task . TaskName , out taskItem ))
{
taskItem . Cancel () ;
m _ taskList . Remove ( task . TaskName ) ;
// create again
var newTask = new ContinuousTaskItem ( task ) ;
m _ taskList . Add ( task . TaskName , newTask ) ;
newTask . Create () ;
}
}
}
) ;
var item = new ContinuousTaskItem ( task ) ;
m _ taskList . Add ( task . TaskName , item ) ;
item . Create () ;
return true ;
}
return false ;
}
}
public bool RemoveTask ( string taskName )
{
lock ( m _ taskList )
{
// delete task
ContinuousTaskItem taskItem = null ;
if ( m _ taskList . TryGetValue ( taskName , out taskItem ))
{
taskItem . Cancel () ;
m _ taskList . Remove ( taskName ) ;
return true ;
}
}
return false ;
}
public void Clear ()
{
lock ( m _ taskList )
{
foreach ( var task in m _ taskList . Values )
{
task . Cancel () ;
}
m _ taskList . Clear () ;
}
}
}