• 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.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
    • 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.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
      • Examples
        • NodeCount
        • Expression
        • Mapper
      • Articles
        • Benchmarks
        • Error Handling
        • ServiceMessages
    • Avalanche.StatusCode
      • Introduction
      • HResult
        • Introduction
        • HResult.Facilities
        • BasicMessages
        • RpcMessages
        • DispatchMessages
        • ItfMessages
        • Win32Messages
        • ClrMessages
      • 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
      • String
        • IEscaper
        • UnicodeString
      • Miscellaneous
        • IIdGenerator
        • Permutation
        • IReadOnly
        • IUserDataContainer
        • Void
    • Avalanche.Writer
      • Introduction
      • ConstantWriter
      • Context
      • ConvertWriter
      • DefaultConstructor
      • DelegateWriter
      • PassthroughWriter
      • Referer
      • TypeCast
      • Writer
      • WriterPipe
      • WriterMessages

    IServiceDisposable

    IServiceDisposable and IServiceDisposable<Request,Response> expose IDisposable.

    /// <summary>Disposable service</summary>
    /// <remarks>Compound of two interfaces is used in methods that need to indicate on return type both properties.</remarks>
    public interface IServiceDisposable : IService, IDisposable { }
    /// <summary>Disposable service</summary>
    /// <remarks>Compound of two interfaces is used in methods that need to indicate on return type both properties.</remarks>
    public interface IServiceDisposableT : IServiceT, IDisposable { }
    /// <summary>Disposable service</summary>
    /// <remarks>Compound of two interfaces is used in methods that need to indicate on return type both properties.</remarks>
    public interface IServiceDisposable<Request> : IService<Request>, IDisposable where Request : notnull { }
    /// <summary>Disposable service</summary>
    /// <remarks>Compound of two interfaces is used in methods that need to indicate on return type both properties.</remarks>
    public interface IServiceOfDisposable<Response> : IServiceOf<Response>, IDisposable { }
    /// <summary>Disposable service</summary>
    /// <remarks>Compound of two interfaces is used in methods that need to indicate on return type both properties.</remarks>
    public interface IServiceDisposable<Request, Response> : IService<Request, Response>, IDisposable where Request : notnull { }
    

    Services.Create() creates a IServiceDisposable. The using statement invokes .Dispose() at closing of block { }.

    using IServiceDisposable service = Services.Create(ServiceHandlers.Instance);
    

    Services.Create<>() constructs a IServiceDisposable<>.

    using IServiceDisposable<object,object> service = Services.Create<object, object>(ServiceHandlers.Instance);
    

    Cache and Entry Policy

    EntryPolicy determines whether cached entries are disposed and whether reference is nulled.

    // Named semaphore factory
    Action<IQuery<string, Semaphore>> semaphoreFactory = q => q.Response.SetValue(new Semaphore(0, 1));
    // Create service with cache and dispose policy
    IServiceDisposable<string, Semaphore> service = Services.Create<string, Semaphore>(semaphoreFactory, CachePolicies.DefaultYes, default, EntryPolicies.DisposeAndNull);
    // Create named semaphore
    Semaphore semaphoreA = service.GetRequired("A");
    // Dipose service and cached semaphores.
    service.Dispose();
    // throws ObjectDisposeException
    semaphoreA.WaitOne();
    

    If no policy is provided, service doesn't cache any result and won't need dispose.

    // Create service without cache
    IService service = Services.Create(ServiceHandlers.Instance, cachePolicy: null);
    

    Cached results that implement IDisposable are disposed along with service, if dispose flag is attached to entry.

    // Named semaphore factory
    Action<IQuery<string, Semaphore>> semaphoreFactory = q => q.Response.SetValue(new Semaphore(0, 1));
    // Choose cache policy (Yes to all requests)
    IRequestPolicy<CachePolicy> cachePolicy = CachePolicies.DefaultYes;
    // Choose entry policy: Cached entries are disposed and nulled with service
    IRequestPolicy<EntryPolicy> entryPolicy = EntryPolicies.DisposeAndNull;
    // Create service with cache
    IServiceDisposable<string, Semaphore> service = Services.Create<string, Semaphore>(semaphoreFactory, cachePolicy, default, entryPolicy);
    // Get-or-create named semaphores
    Semaphore semaphoreA = service.GetRequired("A");
    Semaphore semaphoreB = service.GetRequired("B");
    // Get semaphore "A" 
    Semaphore semaphoreAagain = service.GetRequired("A");
    // Test if we get same reference
    WriteLine( semaphoreA.Equals(semaphoreAagain) ); // "True"
    // Dispose service and all its cached semaphores
    service.Dispose();
    

    If no result type needs dispose, then service doesn't either, and can be left to be garbage collected.

    // Handler
    Action<IQuery<string, string>> suffixAppender = q => q.Response.SetValue(q.Request + "-SUFFIX");
    // Create service with cache
    IServiceDisposable<string, string> service = Services.Create<string, string>(suffixAppender, CachePolicies.DefaultYes, default, EntryPolicies.DisposeAndNull);
    // Get string
    string s1 = service.GetRequired("Hello");
    // Get same cached string
    string s2 = service.GetRequired("Hello");
    // Test if cached, test if references are same
    WriteLine(Object.ReferenceEquals(s1, s2));
    // Append suffix
    WriteLine(s1);
    

    Dispose Attachables

    .AttachDisposable(disposable) attaches an object to be disposed along with service.

    // Create a lock which must be disposed
    ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
    // Handler
    Action<IQuery<string, string>> suffixAppender = q =>
    {
        _lock.EnterWriteLock();
        q.Response.SetValue(q.Request + "-SUFFIX");
        _lock.ExitWriteLock();
    };
    // Create service with cache
    IServiceDisposable<string, string> service = Services.Create<string, string>(suffixAppender, CachePolicies.DefaultYes, default, EntryPolicies.DisposeAndNull);
    // Attach lock for dispose
    (service as IDisposeAttachable)!.AttachDisposable(_lock);
    // Query
    string text = service.GetRequired("Hello");
    // Dispose service and lock
    service.Dispose();
    

    .AttachDisposeAction(func, state) attaches a delegate to be executed at dispose.

    // Create service with cache
    IServiceDisposable service = Services.Create(ServiceHandlers.Instance, CachePolicies.DefaultYes);
    // Create dispose action
    Action<object> action = state => Console.WriteLine("Disposed");
    // Attach lock for dispose
    (service as IDisposeAttachable)!.AttachDisposeAction(action, null!);
    // Dispose service
    service.Dispose();
    

    Belate Dispose

    .BelateDispose() creates a handle that post-pones dispose. Dispose is carried out when service itself and all belate handles are disposed. This is typically used for passing ownership to other thread(s).

    // Create service with cache
    IServiceDisposable<string, string> service = Services.Create<string, string>(ServiceHandlers.Instance, CachePolicies.Default);
    // Create belate handle
    IDisposable belateHandle = (service as IDisposeBelatable)!.BelateDispose();
    // Dispose service (not carried out yet)
    service.Dispose();
    // Dispose belate handle (carries out dispose)
    belateHandle.Dispose();
    

    Full Example

    Full example
    using System;
    using System.Threading;
    using Avalanche.Service;
    using Avalanche.Utilities;
    using static System.Console;
    
    public class service_dispose
    {
        public static void Run()
        {
            {
                // <01>
                using IServiceDisposable service = Services.Create(ServiceHandlers.Instance);
                // </01>
            }
            {
                // <02>
                using IServiceDisposable<object,object> service = Services.Create<object, object>(ServiceHandlers.Instance);
                // </02>
            }
    
            try
            {
                // <11>
                // Named semaphore factory
                Action<IQuery<string, Semaphore>> semaphoreFactory = q => q.Response.SetValue(new Semaphore(0, 1));
                // Create service with cache and dispose policy
                IServiceDisposable<string, Semaphore> service = Services.Create<string, Semaphore>(semaphoreFactory, CachePolicies.DefaultYes, default, EntryPolicies.DisposeAndNull);
                // Create named semaphore
                Semaphore semaphoreA = service.GetRequired("A");
                // Dipose service and cached semaphores.
                service.Dispose();
                // throws ObjectDisposeException
                semaphoreA.WaitOne();
                // </11>
            }
            catch (ObjectDisposedException) { }
    
            {
                // <12>
                // Named semaphore factory
                Action<IQuery<string, Semaphore>> semaphoreFactory = q => q.Response.SetValue(new Semaphore(0, 1));
                // Choose cache policy (Yes to all requests)
                IRequestPolicy<CachePolicy> cachePolicy = CachePolicies.DefaultYes;
                // Choose entry policy: Cached entries are disposed and nulled with service
                IRequestPolicy<EntryPolicy> entryPolicy = EntryPolicies.DisposeAndNull;
                // Create service with cache
                IServiceDisposable<string, Semaphore> service = Services.Create<string, Semaphore>(semaphoreFactory, cachePolicy, default, entryPolicy);
                // Get-or-create named semaphores
                Semaphore semaphoreA = service.GetRequired("A");
                Semaphore semaphoreB = service.GetRequired("B");
                // Get semaphore "A" 
                Semaphore semaphoreAagain = service.GetRequired("A");
                // Test if we get same reference
                WriteLine( semaphoreA.Equals(semaphoreAagain) ); // "True"
                // Dispose service and all its cached semaphores
                service.Dispose();
                // </12>
            }
            {
                // <13>
                // Create service without cache
                IService service = Services.Create(ServiceHandlers.Instance, cachePolicy: null);
                // </13>
            }
            {
                // <14>
                // Handler
                Action<IQuery<string, string>> suffixAppender = q => q.Response.SetValue(q.Request + "-SUFFIX");
                // Create service with cache
                IServiceDisposable<string, string> service = Services.Create<string, string>(suffixAppender, CachePolicies.DefaultYes, default, EntryPolicies.DisposeAndNull);
                // Get string
                string s1 = service.GetRequired("Hello");
                // Get same cached string
                string s2 = service.GetRequired("Hello");
                // Test if cached, test if references are same
                WriteLine(Object.ReferenceEquals(s1, s2));
                // Append suffix
                WriteLine(s1);
                // </14>
            }
    
            // Dispose Attachable
            {
                // <21>
                // Create a lock which must be disposed
                ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
                // Handler
                Action<IQuery<string, string>> suffixAppender = q =>
                {
                    _lock.EnterWriteLock();
                    q.Response.SetValue(q.Request + "-SUFFIX");
                    _lock.ExitWriteLock();
                };
                // Create service with cache
                IServiceDisposable<string, string> service = Services.Create<string, string>(suffixAppender, CachePolicies.DefaultYes, default, EntryPolicies.DisposeAndNull);
                // Attach lock for dispose
                (service as IDisposeAttachable)!.AttachDisposable(_lock);
                // Query
                string text = service.GetRequired("Hello");
                // Dispose service and lock
                service.Dispose();
                // </21>
            }
            // Dispose Action
            {
                // <22>
                // Create service with cache
                IServiceDisposable service = Services.Create(ServiceHandlers.Instance, CachePolicies.DefaultYes);
                // Create dispose action
                Action<object> action = state => Console.WriteLine("Disposed");
                // Attach lock for dispose
                (service as IDisposeAttachable)!.AttachDisposeAction(action, null!);
                // Dispose service
                service.Dispose();
                // </22>
            }
    
            // Belated Dispose
            {
                // <31>
                // Create service with cache
                IServiceDisposable<string, string> service = Services.Create<string, string>(ServiceHandlers.Instance, CachePolicies.Default);
                // Create belate handle
                IDisposable belateHandle = (service as IDisposeBelatable)!.BelateDispose();
                // Dispose service (not carried out yet)
                service.Dispose();
                // Dispose belate handle (carries out dispose)
                belateHandle.Dispose();
                // </31>
            }
    
        }
    }
    
    In This Article
    Back to top Copyright © Toni Kalajainen