view Implab/ComponentContainer.cs @ 130:671f60cd0250 v2

fixed Resove method bug when calling it on already cancelled promise
author cin
date Fri, 30 Jan 2015 17:07:17 +0300
parents 2573b562e328
children
line wrap: on
line source

using System;
using Implab.Parallels;
using System.Threading;

namespace Implab {
    public class ComponentContainer : IComponentContainer, IDisposable {
        static readonly ComponentContainer _appContainer;

        static ComponentContainer() {
            _appContainer = new ComponentContainer();
            AppDomain.CurrentDomain.ProcessExit += HandleProcessExit;
        }

        public static ComponentContainer Global {
            get {
                return _appContainer;
            }
        }

        bool m_disposed;
        readonly AsyncQueue<IDisposable> m_components = new AsyncQueue<IDisposable>();

        public void Add(IDisposable item) {
            Safe.ArgumentNotNull(item, "item");
            Thread.MemoryBarrier();
            if (m_disposed) {
                item.Dispose();
            } else {
                m_components.Enqueue(item);
                if (m_disposed && m_components.TryDequeue(out item))
                    item.Dispose();
            }
        }

        public void Dispose() {
            m_disposed = true;
            IDisposable item;
            while (m_components.TryDequeue(out item))
                item.Dispose();
        }

        static void HandleProcessExit (object sender, EventArgs e)
        {
            _appContainer.Dispose();
        }
    }
}