forked from cschladetsch/CsharpFlow
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGroup.cs
More file actions
135 lines (109 loc) · 2.55 KB
/
Group.cs
File metadata and controls
135 lines (109 loc) · 2.55 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
// (C) 2012 Christian Schladetsch. See http://www.schladetsch.net/flow/license.txt for Licensing information.
using System.Collections.Generic;
namespace Flow
{
/// <summary>
/// A flow Group contains a collection of other Transients, and fires events when the contents of the group changes.
/// </summary>
internal class Group : Generator<bool>, IGroup
{
/// <inheritdoc />
public event GroupHandler Added;
/// <inheritdoc />
public event GroupHandler Removed;
/// <inheritdoc />
public IEnumerable<ITransient> Contents { get { return _contents; } }
/// <inheritdoc />
public IEnumerable<IGenerator> Generators
{
get
{
foreach (var elem in Contents)
{
var gen = elem as IGenerator;
if (gen == null)
continue;
yield return gen;
}
}
}
internal Group()
{
Resumed += tr => ForEachGenerator(g => g.Resume());
Suspended += tr => ForEachGenerator(g => g.Suspend());
Completed += tr => Clear();
}
/// <inheritdoc />
public void Clear()
{
// all pending adds are aborted
_adds.Clear();
// add all contents as pending deletions
foreach (var tr in Contents)
_dels.Add(tr);
// remove all contents
PerformRemoves();
}
/// <inheritdoc />
public override void Post()
{
PerformPending();
}
/// <inheritdoc />
public void Add(ITransient other)
{
if (Transient.IsNullOrEmpty(other))
return;
if (Contents.ContainsRef(other) || _adds.ContainsRef(other))
return;
_dels.RemoveRef(other);
_adds.Add(other);
}
/// <inheritdoc />
public void Remove(ITransient other)
{
if (other == null)
return;
if (!Contents.ContainsRef(other) || _dels.ContainsRef(other))
return;
_adds.RemoveRef(other);
_dels.Add(other);
}
void ForEachGenerator(Action<IGenerator> act)
{
foreach (var gen in Generators)
act(gen);
}
protected void PerformPending()
{
PerformAdds();
PerformRemoves();
}
void PerformRemoves()
{
var dels = _dels.ToArray();
foreach (var tr in dels)
{
_contents.RemoveRef(tr);
tr.Completed -= Remove;
if (Removed != null)
Removed(this, tr);
}
_dels.Clear();
}
void PerformAdds()
{
foreach (var tr in _adds)
{
_contents.Add(tr);
tr.Completed += Remove;
if (Added != null)
Added(this, tr);
}
_adds.Clear();
}
protected readonly List<ITransient> _adds = new List<ITransient>();
protected readonly List<ITransient> _dels = new List<ITransient>();
private readonly List<ITransient> _contents = new List<ITransient>();
}
}