-
Notifications
You must be signed in to change notification settings - Fork 5
/
ContextMonitor.cs
100 lines (88 loc) · 3.19 KB
/
ContextMonitor.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
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
/****************************************************************************
(c) 2012 Steven Houben(shou@itu.dk) and Søren Nielsen(snielsen@itu.dk)
Pervasive Interaction Technology Laboratory (pIT lab)
IT University of Copenhagen
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU GENERAL PUBLIC LICENSE V3 or later,
as published by the Free Software Foundation. Check
http://www.gnu.org/licenses/gpl.html for details.
****************************************************************************/
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace NooSphere.ActivitySystem.Context
{
public class ContextMonitor
{
#region Properties
public Dictionary<Guid,IContextService> Services { get; set; }
public List<Task> Tasks { get; set; }
public bool Running { get; set; }
#endregion
#region Private Members
private readonly CancellationTokenSource _cancellation = new CancellationTokenSource();
#endregion
#region Events
public event DataReceivedHandler DataReceived = null;
public event EventHandler Started = null;
public event EventHandler Stopped = null;
#endregion
#region Constructor
public ContextMonitor(Dictionary<Guid,IContextService> services =null)
{
if (services == null)
Services = new Dictionary<Guid, IContextService>();
else
Services = services;
Running = false;
}
public void Start()
{
Tasks = new List<Task>(Services.Count);
foreach (var contextService in Services.Values)
{
var service = contextService;
Tasks.Add(StartService(service));
}
if(Started !=null)
Started(this, new EventArgs());
}
private Task StartService(IContextService service)
{
return
Task.Factory.StartNew(()=>
{
service.DataReceived += ContextServiceDataReceived;
service.Start();
}, _cancellation.Token);
}
public void Stop()
{
foreach (var contextService in Services.Values)
{
contextService.DataReceived -= ContextServiceDataReceived;
contextService.Stop();
}
_cancellation.Cancel();
if (Stopped != null)
Stopped(this, new EventArgs());
}
public void AddContextService(IContextService service)
{
Services.Add(service.Id, service);
}
public void RemoveContextService(Guid id)
{
Services.Remove(id);
}
#endregion
#region Private Members
private void ContextServiceDataReceived(object sender, DataEventArgs e)
{
if (DataReceived != null)
DataReceived(sender, e);
}
#endregion
}
}