• Avalanche.Core
Search Results for

    Show / Hide Table of Contents
    • Avalanche.Accessor
      • Introduction
      • IAccessor
        • IAccessor
        • IListAccessor
        • IMapAccessor
        • IRecordAccessor
        • IContentAccessor
        • IOneOfAccessor
        • IAnyAccessor
      • .Net
        • Introduction
        • IList<T>
        • IDictionary<K,V>
        • FieldInfo
        • OneOfAttribute
        • StructLayoutAttribute
        • Class
      • Protobuf
        • Introduction
      • Articles
        • Dependency Injection
        • AccessorMessages
    • Avalanche.Binding
      • Introduction
    • Avalanche.Configuration
      • Introduction
      • Configuration Binding
      • ConfigurationExtensions
      • MemoryConfiguration
      • PrintTree
      • Saving IOptions
      • Yaml
    • Avalanche.Converter
      • Introduction
      • EnumConverter
      • Func<,>
      • HexConverter
      • PrimitiveConverter
      • StringConverter
    • Avalanche.Core
      • License
    • Avalanche.DataType
      • Introduction
      • DataType
        • IDataType
        • IListType
        • IMapType
        • IRecordType
        • IFieldType
        • IOneOfType
        • IAnyType
        • IStringType
        • IValueType
        • IIntegerType
        • IEnumerationType
        • IRealType
      • .Net
        • Introduction
        • IList<T>
        • IDictionary<K,V>
        • FieldInfo
        • Enum
        • OneOfAttribute
        • StructLayoutAttribute
        • Class
      • Protobuf
        • Introduction
      • Articles
        • DataTypeRequest
        • PrintTree
        • DataTypeMessages
    • Avalanche.Emit
      • Introduction
      • TypeBuilder
      • ConstructorBuilder
      • MethodBuilder
      • PropertyBuilder
      • FieldBuilder
      • Emit
      • Utilities
    • Avalanche.FileSystem
      • Introduction
      • Abstractions
        • IFileSystem
          • IFileSystemBrowse
          • IFileSystemCreateDirectory
          • IFileSystemDelete
          • IFileSystemFileAttribute
          • IFileSystemMount
          • IFileSystemMove
          • IFileSystemObserve
          • IFileSystemOpen
        • IEvent
        • IEntry
        • IOption
        • IToken
      • FileSystem
      • VirtualFileSystem
      • MemoryFileSystem
      • EmbeddedFileSystem
      • HttpFileSystem
      • Decoration
      • IFileProvider
      • Events
      • Utilities
        • Dispose
        • File Scanner
        • Visit Tree
        • File Operation
        • FilterEnumerable
        • PollingFilterWatchToken
    • Avalanche.Identity
      • Introduction
      • Identity
      • IdentityParts
      • IdentityInterner
      • IdentityComparer
      • Print Tree
      • IdentityAccessors
        • Introduction
        • TypeName
    • Avalanche.Localization
      • Introduction
      • Localization
      • LocalizationFile
      • LocalizationFiles
      • LocalizationFileSystem
      • LocalizationFileFormat
      • LocalizationLine
      • LocalizationLines
      • TemplateFormat
      • CultureProvider
      • FallbackCultureProvider
      • ResourceManager
      • LocalizationError
      • Microsoft.Extensions
        • Introduction
        • DependencyInjection
        • FileProvider
        • Logging
        • ITextLocalizer
        • IFileLocalizer
        • Localization
      • Asp.Net
        • Introduction
        • Supplying localization
        • Inject to pages
        • Culture Assigned
        • Minimalistic Api
        • Diagnostics
      • Pluralization
        • Introduction
        • Multiple plural parameters
        • Custom PluralRules
        • Invariant Culture
        • Unit Prefix
        • IPluralRule
        • IPluralNumber
        • IPluralRules
        • CLDRs
        • Unicode.CLDR40
        • Unicode.CLDR41
        • Unicode.CLDR42
      • Articles
        • Alphabet localization
        • Benchmarks
        • Caching
        • Class Library
        • Demo
        • Diagnostics
        • Embedded resources
        • Emplacement
        • File localization
        • Text localization
        • Printing templates
    • Avalanche.Message
      • Introduction
      • IMessage
      • IMessageProvider
      • IMessageDescription
      • IMessageDescriptions
      • MessageLevel
      • Message printing
      • Messages and Exceptions
      • Microsoft.Extensions
        • DependencyInjection
      • Articles
        • Aggregate Messages
        • Localization
        • Logging
        • Validation
    • Avalanche.Options
      • Introduction
      • OptionsExtensions
      • OptionsMonitorCast
    • Avalanche.Service
      • Introduction
      • Service
        • Introduction
        • IService
        • IServiceDisposable
        • IServiceDecoration
        • IServiceCast
        • IServiceObservable
        • IServiceContainer
        • Construction
        • Query
        • CancellationToken
        • CachePolicy
        • Scope
      • Handler
        • Introduction
        • IHandler
        • IHandlerCast
        • IHandlerDecoration
        • IHandlerWithOrder
        • CancellationToken
        • Cyclicity
        • Delegates
        • Invokable
        • ExportAttribute
        • OrderAttribute
        • PrintTree
        • Recursion
      • Query
        • Introduction
        • IQuery
        • IQueryCast
        • IQueryDecoration
      • Entry
        • Introduction
        • IEntry
        • IEntryCast
        • IEntryDecoration
        • IEntryObservable
        • IEntryVisitable
        • EntryState
      • Request
        • Introduction
        • IRequest
        • IRequestFor
        • IRequestToBeCached
        • IRequestToBeDisposed
        • RequestAttribute
        • ContextParameterAttribute
        • Print Tree
      • Dependency Injection
        • Introduction
        • Asp.Net
        • ServiceRequest<T>
        • Decorating a service
        • Handler
        • CachePolicy
        • CancellationToken
        • QueryLogger
        • IHostBuilder
      • Examples
        • NodeCount
        • Expression
        • Mapper
      • Articles
        • Benchmarks
        • Error Handling
        • ServiceMessages
    • Avalanche.StatusCode
      • Introduction
      • HResult
        • Introduction
        • HResult.Facilities
        • BasicMessages
        • RpcMessages
        • DispatchMessages
        • StorageMessages
        • ItfMessages
        • Win32Messages
        • WindowsMessages
        • SspiMessages
        • CertMessages
        • MediaServerMessages
        • SetupApiMessages
        • ScardMessages
        • ComPlusMessages
        • ClrMessages
        • UserModeFilterManagerMessages
        • GraphicsMessages
        • TpmServicesMessages
        • TpmSoftwareMessages
        • PlaMessages
        • FveMessages
        • FwpMessages
        • NdisMessages
        • DltMessages
      • System
        • Introduction
        • AccessControlMessages
        • AggregateMessages
        • AppDomainMessages
        • ArgumentMessages
        • ArgumentNullMessages
        • ArgumentOutOfRangeMessages
        • ArithmeticMessages
        • ArrayMessages
        • AssemblyMessages
        • BadImageFormatMessages
        • CodeContractMessages
        • CodePageMessages
        • CollectionsMessages
        • CompilerServiceMessages
        • CryptographyMessages
        • CultureMessages
        • DiagnosticsMessages
        • EventSourceMessages
        • ExecutionEngineMessages
        • FormatMessages
        • HostProtectionMessages
        • IOMessages
        • IndexOutOfRangeMessages
        • InteropServiceMessages
        • InvalidCastMessages
        • InvalidOperationMessages
        • IsolatedStorageMessages
        • LazyMessages
        • MarshalerMessages
        • MemoryMessages
        • MiscellaneousMessages
        • NotImplementedMessages
        • NotSupportedMessages
        • ObjectDisposedMessages
        • OperationCanceledMessages
        • OverflowMessages
        • PlatformMessages
        • PolicyMessages
        • PrincipalMessages
        • ProgramMessages
        • ReferenceMessages
        • ReflectionMessages
        • RegionMessages
        • RemotingMessages
        • ResourcesMessages
        • SecurityMessages
        • SerializationMessages
        • StackMessages
        • TaskMessages
        • TextMessages
        • ThreadingMessages
        • TimeZoneMessages
        • TypeMessages
        • XmlMessages
      • HttpStatusCode
      • OpcUaStatusCode
    • Avalanche.Template
      • Introduction
      • TemplateFormats
      • ITemplatePrintable
      • ITemplateFormatPrintable
      • ITemplateText
      • ITemplateBreakdown
      • ITemplateFormat
      • ITemplateFormats
      • Extract Arguments
      • Emplacement
    • Avalanche.Tokenizer
      • Introduction
      • IToken
      • ITokenizer
      • Tokenizers
    • Avalanche.Utilities
      • Introduction
      • Collections
        • Tuples
        • StructList
        • ArrayList
        • BijectionMap
        • LocakableDictionary
        • LockableList
        • MapList
        • Pipe
        • RingQueue
        • EnumerableExtensions
        • TupleUtilities
        • ArrayUtilities
      • Comparers
        • IGraphComparer
        • IGraphComparable
        • AlphaNumericComparer
        • EnumerableComparer
        • EnumerableGraphComparer
        • ReferenceComparer
        • KeyValuePairComparer
        • DefaultComparerProvider
        • RecordComparer
      • Cloners
        • ICloner
        • IGraphCloner
        • IGraphCloneable
        • ListCloner
        • DictionaryCloner
        • FieldCloner
        • PassthroughCloner
        • RecordCloner
        • ClonerProvider
      • Dispose
        • IDisposeAttachable
        • IDisposeBelatable
      • Provider
        • Introduction
        • ProviderBase
        • Delegate
        • Pipe
        • Cache
        • ResultCapture
        • AsReadOnly
        • AsService
        • IProviderEvent
      • Record
        • IRecordDescription
        • IFieldDescription
        • IConstructorDescription
        • IConstructionDescription
        • IParameterDescription
        • IRecordProviders
        • RecordDelegates
          • RecordCreate
          • RecordClone
          • RecordCopy
          • IRecordDelegates
        • FieldDelegates
          • FieldRead
          • FieldWrite
          • RecreateWith
          • IFieldDelegates
      • Reflection
        • EnumDescription
      • String
        • IEscaper
        • UnicodeString
        • Hex
      • Miscellaneous
        • IIdGenerator
        • Permutation
        • IReadOnly
        • IUserDataContainer
        • ITreeNode
        • Void
    • Avalanche.Writer
      • Introduction
      • ConstantWriter
      • Context
      • ConvertWriter
      • DefaultConstructor
      • DelegateWriter
      • PassthroughWriter
      • Referer
      • TypeCast
      • Writer
      • WriterPipe
      • WriterMessages

    IDisposeAttachable

    IDisposeAttachable is an interface for classes where disposable objects can be attached.

    /// <summary>
    /// Object where <see cref="IDisposable"/>s can be attached. Attachments will be disposed along with the object.
    /// 
    /// There are four stages of dispose: NotDisposed, DisposeCalled, Disposing, Disposed.
    /// If dispose is belated, then dispose call won't start internal dispose until belatables are cleared.
    /// </summary>
    public interface IDisposeAttachable : IDisposable
    {
        /// <summary>Has <see cref="IDisposable.Dispose"/> been called whether or not internal dispose has started. Internal dispose starts when all belatables are disposed.</summary>
        bool IsDisposeCalled { get; }
        /// <summary>Has internal dispose started or completed.</summary>
        bool IsDisposing { get; }
        /// <summary>Has dispose completed.</summary>
        bool IsDisposed { get; }
    
        /// <summary>
        /// Attach <paramref name="disposable"/> to be disposed along with this object.
        /// 
        /// If the implementing object has already been disposed, this method immediately disposes the <paramref name="disposable"/>.
        /// </summary>
        /// <param name="disposable"></param>
        /// <returns>true if was added to list, false if wasn't but was disposed immediately</returns>
        bool AttachDisposable(object disposable);
    
        /// <summary>
        /// Attach <paramref name="disposableObjects"/> to be disposed along with this object.
        /// 
        /// If the implementing object has already been disposed, this method immediately disposes the <paramref name="disposableObjects"/>.
        /// </summary>
        /// <param name="disposableObjects"></param>
        /// <returns>true if were added to list, false if were disposed immediately</returns>
        bool AttachDisposables(IEnumerable<object> disposableObjects);
    
        /// <summary>
        /// Remove <paramref name="disposableObject"/> from the attachables. 
        /// </summary>
        /// <param name="disposableObject"></param>
        /// <returns>true if was removed, false if it wasn't in the list.</returns>
        bool RemoveDisposable(object disposableObject);
    
        /// <summary>
        /// Remove <paramref name="disposableObjects"/> from the attachables 
        /// </summary>
        /// <param name="disposableObjects"></param>
        /// <returns>true if was removed, false if it wasn't in the list.</returns>
        bool RemoveDisposables(IEnumerable<object> disposableObjects);
    
        /// <summary>
        /// Attach <paramref name="disposeAction"/> to be executed on dispose of this object.
        /// 
        /// If parent object is disposed or being disposed, the <paramref name="disposeAction"/> is executed immediately.
        /// </summary>
        /// <param name="disposeAction"></param>
        /// <param name="state"></param>
        /// <returns>true if was added to list, false if was disposed right away</returns>
        bool AttachDisposeAction(Action<object> disposeAction, object? state);
    }
    

    .AttachDisposable(object) extension method (Namespace Avalanche.Core, Avalanche.Utilities.Abstractions.dll) attaches an object to be disposed along with the target object.

    // Create something disposable
    IDisposable s = new Semaphore(1, 1);
    // Create obj and attach disposable
    MyClass obj = new MyClass().AttachDisposable(s);
    // Dispose 'obj' and attached 's'
    obj.Dispose();
    

    .RemoveDisposable() removes attachment.

    obj.RemoveDisposable(s);
    

    .AddDisposeAction(Action<T>) attaches a dispose action.

    MyClass obj = new MyClass().AddDisposeAction((MyClass m) => { });
    

    DisposeAttachable can be used as base class for IDisposeAttachable implementations.

    public class MyClass : DisposeAttachable, IDisposeAttachable
    {
    }
    

    InnerDispose() and InnerDisposeUnmanaged() can be overridden for internal dispose procedure.

    public class MyClassB : DisposeAttachable, IDisposeAttachable
    {
        /// <summary>Override this to dispose managed resources</summary>
        /// <param name="errors">list that can be instantiated and where errors can be added</param>
        /// <exception cref="Exception">any exception is captured and aggregated with other errors</exception>
        protected override void InnerDispose<Exceptions>(ref Exceptions errors)
        {
        }
    
        /// <summary>Override this to dispose unmanaged resources.</summary>
        /// <param name="errors">list that can be instantiated and where errors can be added</param>
        /// <exception cref="Exception">any exception is captured and aggregated with other errors</exception>
        protected override void InnerDisposeUnmanaged<Exceptions>(ref Exceptions errors)
        {
        }
    }
    

    Full Example

    Full example
    using System;
    using System.Threading;
    using Avalanche.Utilities;
    
    class disposeattachable
    {
        public static void Run()
        {
            {
                // <01>
                // Create something disposable
                IDisposable s = new Semaphore(1, 1);
                // Create obj and attach disposable
                MyClass obj = new MyClass().AttachDisposable(s);
                // Dispose 'obj' and attached 's'
                obj.Dispose();
                // </01>
            }
            {
                // Create something disposable
                IDisposable s = new Semaphore(1, 1);
                // Create obj and attach disposable
                MyClass obj = new MyClass().AttachDisposable(s);
                // <02>
                obj.RemoveDisposable(s);
                // </02>
            }
            {
                // <03>
                MyClass obj = new MyClass().AddDisposeAction((MyClass m) => { });
                // </03>
            }
        }
    
        // <10>
        public class MyClass : DisposeAttachable, IDisposeAttachable
        {
        }
        // </10>
    
        // <11>
        public class MyClassB : DisposeAttachable, IDisposeAttachable
        {
            /// <summary>Override this to dispose managed resources</summary>
            /// <param name="errors">list that can be instantiated and where errors can be added</param>
            /// <exception cref="Exception">any exception is captured and aggregated with other errors</exception>
            protected override void InnerDispose<Exceptions>(ref Exceptions errors)
            {
            }
    
            /// <summary>Override this to dispose unmanaged resources.</summary>
            /// <param name="errors">list that can be instantiated and where errors can be added</param>
            /// <exception cref="Exception">any exception is captured and aggregated with other errors</exception>
            protected override void InnerDisposeUnmanaged<Exceptions>(ref Exceptions errors)
            {
            }
        }
        // </11>
    }
    
    In This Article
    Back to top Copyright © Toni Kalajainen