Debian Codegraph @

external/rx/Rx/NET/Source/System.Reactive.Core/Reactive/Disposables/SerialDisposable.cs

raw
1 // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
2
3 namespace System.Reactive.Disposables
4 {
5 /// <summary>
6 /// Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource.
7 /// </summary>
8 public sealed class SerialDisposable : ICancelable
9 {
10 private readonly object _gate = new object();
11 private IDisposable _current;
12 private bool _disposed;
13
14 /// <summary>
15 /// Initializes a new instance of the <see cref="T:System.Reactive.Disposables.SerialDisposable"/> class.
16 /// </summary>
17 public SerialDisposable()
18 {
19 }
20
21 /// <summary>
22 /// Gets a value that indicates whether the object is disposed.
23 /// </summary>
24 public bool IsDisposed
25 {
26 get
27 {
28 lock (_gate)
29 {
30 return _disposed;
31 }
32 }
33 }
34
35 /// <summary>
36 /// Gets or sets the underlying disposable.
37 /// </summary>
38 /// <remarks>If the SerialDisposable has already been disposed, assignment to this property causes immediate disposal of the given disposable object. Assigning this property disposes the previous disposable object.</remarks>
39 public IDisposable Disposable
40 {
41 get
42 {
43 return _current;
44 }
45
46 set
47 {
48 var shouldDispose = false;
49 var old = default(IDisposable);
50 lock (_gate)
51 {
52 shouldDispose = _disposed;
53 if (!shouldDispose)
54 {
55 old = _current;
56 _current = value;
57 }
58 }
59 if (old != null)
60 old.Dispose();
61 if (shouldDispose && value != null)
62 value.Dispose();
63 }
64 }
65
66 /// <summary>
67 /// Disposes the underlying disposable as well as all future replacements.
68 /// </summary>
69 public void Dispose()
70 {
71 var old = default(IDisposable);
72
73 lock (_gate)
74 {
75 if (!_disposed)
76 {
77 _disposed = true;
78 old = _current;
79 _current = null;
80 }
81 }
82
83 if (old != null)
84 old.Dispose();
85 }
86 }
87 }