-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDisposableSet.cs
109 lines (96 loc) · 3.04 KB
/
DisposableSet.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
101
102
103
104
105
106
107
108
109
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ReactiveProperties.Utils
{
/// <summary>
/// A utility class that takes a list of disposables and dispose them all when its disposed.
/// </summary>
public class DisposableSet : IDisposable
{
private readonly HashSet<IDisposable> _Set = new HashSet<IDisposable>();
private bool _Disposed;
public DisposableSet() { }
public DisposableSet(IEnumerable<IDisposable> disposables)
{
AddRange(disposables);
}
public DisposableSet(params IDisposable[] disposables)
: this(disposables.AsEnumerable()) { }
/// <summary>
/// Adds a single disposable.
/// </summary>
/// <param name="obj">The disposable to add.</param>
public void Add(IDisposable obj)
{
_Set.Add(obj);
}
/// <summary>
/// Adds a list of disposables.
/// </summary>
/// <param name="objs">A list of disposables.</param>
public void AddRange(IEnumerable<IDisposable> objs)
{
foreach (var item in objs)
_Set.Add(item);
}
/// <summary>
/// Adds a list of disposables.
/// </summary>
/// <param name="objs">A list of disposables.</param>
public void AddRange(params IDisposable[] objs)
{
AddRange((IEnumerable<IDisposable>)objs);
}
/// <summary>
/// Removes the given disposable without disposing it.
/// </summary>
/// <param name="obj">The disposable to remove.</param>
/// <returns>true if the element is successfully found and removed; otherwise, false.</returns>
public bool Remove(IDisposable obj)
{
return _Set.Remove(obj);
}
/// <summary>
/// Removes the given disposable and disposes it.
/// </summary>
/// <param name="obj">The disposable to remove and dispose.</param>
/// <returns>true if the element is successfully found and removed; otherwise, false.</returns>
public void RemoveAndDispose(IDisposable obj)
{
_Set.Remove(obj);
obj.Dispose();
}
/// <summary>
/// Removes and disposes all members.
/// </summary>
public void RemoveAndDisposeAll()
{
foreach (var item in _Set)
item.Dispose();
_Set.Clear();
}
protected virtual void Dispose(bool disposing)
{
if (!_Disposed)
{
if (disposing)
{
foreach (var item in _Set)
item.Dispose();
}
}
_Disposed = true;
}
/// <summary>
/// Disposes all the members.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}