Class SharedDisposable<T>
- Namespace
- Kampute.HttpClient.Utilities
- Assembly
- Kampute.HttpClient.dll
Manages shared access to a disposable resource, ensuring it is correctly disposed of when no longer in use.
public sealed class SharedDisposable<T> where T : class, IDisposable
Type Parameters
T
The type of the disposable object. Must be a class that implements IDisposable.
- Inheritance
-
SharedDisposable<T>
- Inherited Members
Remarks
This class is particularly useful for managing resources that are expensive to create and can be safely shared across different parts of an application. It ensures that the resource remains alive as long as it is needed and is properly cleaned up afterwards. This pattern helps prevent resource leaks and promotes efficient resource usage.
The implementation is thread-safe, making it suitable for use in multi-threaded environments where resources may be accessed concurrently. The resource is created lazily, only when it is first requested, and is disposed of when the last reference is released.
Constructors
SharedDisposable()
Initializes a new instance of the SharedDisposable<T> class that uses the default constructor of T
.
public SharedDisposable()
SharedDisposable(Func<T>)
Initializes a new instance of the SharedDisposable<T> class with a factory function.
public SharedDisposable(Func<T> factory)
Parameters
factory
Func<T>A function that creates an instance of the object
T
when needed.
Exceptions
- ArgumentNullException
Thrown if
factory
is null.
Properties
ReferenceCount
Gets the current number of active references to the managed disposable object.
public int ReferenceCount { get; }
Property Value
- int
The number of active references.
Methods
AcquireReference()
Creates a new reference to the shared disposable resource, increasing the reference count.
public SharedDisposable<T>.Reference AcquireReference()
Returns
- SharedDisposable<T>.Reference
A new SharedDisposable<T>.Reference instance.