Debian Codegraph @

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

raw
1 // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
2
3 using System.Threading;
4
5 namespace System.Reactive.Disposables
6 {
7 /// <summary>
8 /// Represents a disposable resource which only allows a single assignment of its underlying disposable resource.
9 /// If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an <see cref="T:System.InvalidOperationException"/>.
10 /// </summary>
11 public sealed class SingleAssignmentDisposable : ICancelable
12 {
13 private volatile IDisposable _current;
14
15 /// <summary>
16 /// Initializes a new instance of the <see cref="T:System.Reactive.Disposables.SingleAssignmentDisposable"/> class.
17 /// </summary>
18 public SingleAssignmentDisposable()
19 {
20 }
21
22 /// <summary>
23 /// Gets a value that indicates whether the object is disposed.
24 /// </summary>
25 public bool IsDisposed
26 {
27 get
28 {
29 // We use a sentinel value to indicate we've been disposed. This sentinel never leaks
30 // to the outside world (see the Disposable property getter), so no-one can ever assign
31 // this value to us manually.
32 return _current == BooleanDisposable.True;
33 }
34 }
35
36 /// <summary>
37 /// Gets or sets the underlying disposable. After disposal, the result of getting this property is undefined.
38 /// </summary>
39 /// <exception cref="InvalidOperationException">Thrown if the SingleAssignmentDisposable has already been assigned to.</exception>
40 public IDisposable Disposable
41 {
42 get
43 {
44 var current = _current;
45
46 if (current == BooleanDisposable.True)
47 return DefaultDisposable.Instance; // Don't leak the sentinel value.
48
49 return current;
50 }
51
52 set
53 {
54 #pragma warning disable 0420
55 var old = Interlocked.CompareExchange(ref _current, value, null);
56 #pragma warning restore 0420
57 if (old == null)
58 return;
59
60 if (old != BooleanDisposable.True)
61 throw new InvalidOperationException(Strings_Core.DISPOSABLE_ALREADY_ASSIGNED);
62
63 if (value != null)
64 value.Dispose();
65 }
66 }
67
68 /// <summary>
69 /// Disposes the underlying disposable.
70 /// </summary>
71 public void Dispose()
72 {
73 #pragma warning disable 0420
74 var old = Interlocked.Exchange(ref _current, BooleanDisposable.True);
75 #pragma warning restore 0420
76 if (old != null)
77 old.Dispose();
78 }
79 }
80 }