public static void RunInContext(ExecutionContext context, ContextCallback callback, object state, bool preserveSyncCtx)
        {
            TurboContract.Requires(context != null, conditionString: "context != null");
            TurboContract.Requires(callback != null, conditionString: "callback != null");

#if NETCOREAPP
            ExecutionContext.Run(context, callback, state);
#else
            var action = _runInContextDelegate ?? InitRunInContextMethod();
            action(context, callback, state, preserveSyncCtx);
#endif
        }
 /// <summary>
 /// <see cref="SendOrPostCallbackSyncThreadPoolWorkItem"/> constructor
 /// </summary>
 /// <param name="action">Delegate to execute work</param>
 /// <param name="state">State object that will be passed to delegate</param>
 /// <param name="allowExecutionContextFlow">Indicates whether the ExecutionContext should be captured</param>
 /// <param name="preferFairness">Indicates whether this work item should alwayes be enqueued to the GlobalQueue</param>
 public SendOrPostCallbackSyncThreadPoolWorkItem(SendOrPostCallback action, object state, bool allowExecutionContextFlow, bool preferFairness)
     : base(allowExecutionContextFlow, preferFairness)
 {
     TurboContract.Requires(action != null, conditionString: "action != null");
     _action          = action;
     _state           = state;
     _isCompleted     = false;
     _isCancelled     = false;
     _exception       = null;
     _syncObject      = new object();
     _taskProcessFlag = 0;
 }
Exemple #3
0
        /// <summary>
        /// Attempts to get the injection object of the specified type
        /// </summary>
        /// <typeparam name="T">The type of requested injection object</typeparam>
        /// <param name="obj">Source InjectionContainer</param>
        /// <param name="val">Resolved object if foundпеха</param>
        /// <returns>True if the injection object is registered for the specified key; overwise false</returns>
        public static bool TryGetInjection <T>(this GenericInjectionContainerBase <Type> obj, out T val)
        {
            TurboContract.Requires(obj != null, conditionString: "obj != null");

            if (obj.TryGetInjection(typeof(T), out object tmpVal))
            {
                val = (T)tmpVal;
                return(true);
            }
            val = default(T);
            return(false);
        }
        /// <summary>
        /// Основной код возвращения элемента в множество свободных
        /// </summary>
        /// <param name="element">Элемент</param>
        private void ReleaseCore(PoolElementWrapper <T> element)
        {
            TurboContract.Requires(element != null, conditionString: "element != null");

            try { }
            finally
            {
                element.MakeAvailable();
                _globalFreeElements.Add(element);
                _occupiedElements.Release();
            }
        }
        /// <summary>
        /// Вернуть элемент в список свободных
        /// </summary>
        /// <param name="element">Элемент</param>
        public void Release(PoolElementWrapper <T> element)
        {
            TurboContract.Requires(element != null, conditionString: "element != null");
            TurboContract.Requires(element.Owner == this, conditionString: "element.Owner == this");

            if (element.IsElementDestroyed)
            {
                PerformRealRemove(element);
                return;
            }

            ReleaseCore(element);
        }
        /// <summary>
        /// Adds a new association to the container
        /// </summary>
        /// <param name="key">Key</param>
        /// <param name="objType">The type of the object that will be held by the lifetime container</param>
        /// <param name="val">Factory to create a lifetime container for the sepcified 'objType'</param>
        protected sealed override void AddAssociationInner(TKey key, Type objType, Lifetime.Factories.LifetimeFactory val)
        {
            TurboContract.Requires(key != null, conditionString: "key != null");
            TurboContract.Requires(objType != null, conditionString: "objType != null");
            TurboContract.Requires(val != null, conditionString: "val != null");

            var lfInf = ProduceResolveInfo(key, objType, val);

            if (!_storage.TryAdd(key, lfInf))
            {
                throw new ItemAlreadyExistsException(string.Format("AssociationContainer already contains the association for the key ({0})", key));
            }
        }
            public object Resolve(Type reqObjectType, string paramName, Type forType, object extData)
            {
                TurboContract.Requires(reqObjectType != null, conditionString: "reqObjectType != null");

                object res = null;

                if (_sourceInj.TryGetInjection(reqObjectType, out res))
                {
                    return(res);
                }

                return(_curLocator.Resolve(reqObjectType));
            }
        /// <summary>
        /// Runs the action within ThreadPool
        /// </summary>
        /// <param name="act">Action to run</param>
        /// <param name="flowContext">Whether or not the exectuion context should be flowed</param>
        void IContextSwitchSupplier.Run(Action act, bool flowContext)
        {
            TurboContract.Requires(act != null, conditionString: "act != null");

            if (flowContext)
            {
                System.Threading.ThreadPool.QueueUserWorkItem(RunActionWaitCallback, act);
            }
            else
            {
                System.Threading.ThreadPool.UnsafeQueueUserWorkItem(RunActionWaitCallback, act);
            }
        }
        /// <summary>
        /// Runs the action within ThreadPool
        /// </summary>
        /// <param name="act">Action to run</param>
        /// <param name="state">State object</param>
        /// <param name="flowContext">Whether or not the exectuion context should be flowed</param>
        void IContextSwitchSupplier.RunWithState(Action <object> act, object state, bool flowContext)
        {
            TurboContract.Requires(act != null, conditionString: "act != null");

            if (flowContext)
            {
                System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(act), state);
            }
            else
            {
                System.Threading.ThreadPool.UnsafeQueueUserWorkItem(new System.Threading.WaitCallback(act), state);
            }
        }
Exemple #10
0
        /// <summary>
        /// Добавить элемент в очередь
        /// </summary>
        /// <param name="item">Элемент</param>
        public void Add(ThreadPoolWorkItem item)
        {
            TurboContract.Requires(item != null, conditionString: "item != null");

            SpinWait sw   = new SpinWait();
            Segment  tail = _tail;

            while (!tail.TryAdd(item))
            {
                sw.SpinOnce();
                tail = _tail;
            }
        }
        /// <summary>
        /// Вычислить среднюю производительность
        /// </summary>
        /// <param name="data">Замеры</param>
        /// <returns>Среднее</returns>
        private static double CalcAverageThroughout(ThroughoutData[] data)
        {
            TurboContract.Requires(data != null, conditionString: "data != null");
            TurboContract.Requires(data.Length > 0, conditionString: "data.Length > 0");

            double res = 0;

            for (int i = 0; i < data.Length; i++)
            {
                res += data[i].Throughout;
            }
            return(res / data.Length);
        }
        /// <summary>
        /// Оценить ожидаемую производительность при изменении числа потоков (влияние считается линейным)
        /// </summary>
        /// <param name="curThreadCount">Предыдущее число потоков</param>
        /// <param name="curThroughout">Предыдущая производительность</param>
        /// <param name="newThreadCount">Новое число потоков</param>
        /// <returns>Оценочная производительность</returns>
        private static double EstimateExpectedThroughout(int curThreadCount, double curThroughout, int newThreadCount)
        {
            TurboContract.Requires(curThreadCount >= 0, conditionString: "curThreadCount >= 0");
            TurboContract.Requires(curThroughout >= 0, conditionString: "curThroughout >= 0");
            TurboContract.Requires(newThreadCount >= 0, conditionString: "newThreadCount >= 0");

            if (curThreadCount == 0)
            {
                return(1.0);
            }

            return((curThroughout / curThreadCount) * newThreadCount);
        }
            public ThroughoutData(int executedTaskCount, double throughout, double averageThroughout, int threadCount, bool isPerfMeasureThreadWork)
            {
                TurboContract.Requires(executedTaskCount >= 0, conditionString: "executedTaskCount >= 0");
                TurboContract.Requires(throughout >= 0, conditionString: "throughout >= 0");
                TurboContract.Requires(averageThroughout >= 0, conditionString: "averageThroughout >= 0");
                TurboContract.Requires(threadCount >= 0, conditionString: "threadCount >= 0");

                ExecutedTaskCount       = executedTaskCount;
                Throughout              = throughout;
                AverageThroughout       = averageThroughout;
                ThreadCount             = threadCount;
                IsPerfMeasureThreadWork = isPerfMeasureThreadWork;
            }
Exemple #14
0
        /// <summary>
        /// Resolves the object held by the container
        /// </summary>
        /// <param name="resolver">Injection resolver to acquire parameters</param>
        /// <returns>Resolved instance of the object</returns>
        /// <exception cref="CommonIoCException">Can be raised when injections not found</exception>
        public sealed override object GetInstance(IInjectionResolver resolver)
        {
            TurboContract.Requires(resolver != null, conditionString: "resolver != null");

            var result = _obj.Value;

            if (!result.IsInitialized)
            {
                result = CreateInstanceCore(resolver);
            }

            return(result.Object);
        }
 /// <summary>
 /// Sets externally created task for passed action
 /// </summary>
 /// <param name="task">Task</param>
 public void SetTask(Task task)
 {
     TurboContract.Requires(task != null, conditionString: "task != null");
     if (_task != null)
     {
         throw new InvalidOperationException("Task already setted");
     }
     if (!object.ReferenceEquals(task.AsyncState, this))
     {
         throw new ArgumentException("Task.AsyncState should be set to this object");
     }
     _task = task;
 }
Exemple #16
0
        /// <summary>
        /// Places a new task to the thread pool queue
        /// </summary>
        /// <param name="item">Thread pool work item</param>
        protected sealed override void AddWorkItem(ThreadPoolWorkItem item)
        {
            TurboContract.Requires(item != null, conditionString: "item != null");

            CheckDisposed();
            if (IsAddingCompleted)
            {
                throw new InvalidOperationException("Adding was completed for ThreadPool: " + Name);
            }

            this.PrepareWorkItem(item);
            this.AddWorkItemToQueue(item);
        }
        // =============================


        /// <summary>
        /// Read single item bytes from disk to <paramref name="targetStream"/> (incuding header)
        /// </summary>
        /// <param name="targetStream">Target stream to read bytes (Position is not changed after read)</param>
        /// <param name="itemSize">Size of the readed item (without header)</param>
        /// <param name="take">Should move readStream position</param>
        /// <returns>Is read</returns>
        private bool TryTakeOrPeekSingleItemBytesFromDisk(MemoryStream targetStream, out int itemSize, bool take)
        {
            TurboContract.Requires(targetStream != null, conditionString: "targetStream != null");
            TurboContract.Assert(Monitor.IsEntered(_readLock), conditionString: "Monitor.IsEntered(_readLock)");

            itemSize = 0;

            long readStreamPosition = _readStream.Position;

            // Ensure capacity on MemoryStream
            targetStream.SetLength(targetStream.Position + ItemHeaderSize);

            // Read item header
            var rawBuffer = targetStream.GetBuffer();
            int readCount = _readStream.Read(rawBuffer, (int)targetStream.Position, ItemHeaderSize);

            if (readCount != ItemHeaderSize) // No space for item header
            {
                if (readCount != 0)
                {
                    _readStream.Seek(-readCount, SeekOrigin.Current); // Rewind back the position
                }
                TurboContract.Assert(_readStream.Position == readStreamPosition, conditionString: "_readStream.Position == readStreamPosition");
                return(false);
            }

            itemSize = BitConverter.ToInt32(rawBuffer, (int)targetStream.Position);

            // Ensure capacity on MemoryStream
            targetStream.SetLength(targetStream.Position + ItemHeaderSize + itemSize);

            // Read item
            rawBuffer = targetStream.GetBuffer();
            readCount = _readStream.Read(rawBuffer, (int)targetStream.Position + ItemHeaderSize, itemSize);
            if (readCount != itemSize)
            {
                _readStream.Seek(-ItemHeaderSize - readCount, SeekOrigin.Current); // Rewind back the position
                TurboContract.Assert(_readStream.Position == readStreamPosition, conditionString: "_readStream.Position == readStreamPosition");
                return(false);
            }

            if (!take)
            {
                // For peek should rewind stream position
                _readStream.Seek(-ItemHeaderSize - itemSize, SeekOrigin.Current);
            }

            TurboContract.Assert(targetStream.Position + ItemHeaderSize + itemSize == targetStream.Length, conditionString: "targetStream.Position + ItemHeaderSize + itemSize == targetStream.Length");
            TurboContract.Assert(take || _readStream.Position == readStreamPosition, conditionString: "take || _readStream.Position == readStreamPosition");
            return(true);
        }
Exemple #18
0
        /// <summary>
        /// <see cref="BatchingQueueSegment{T}"/> constructor
        /// </summary>
        /// <param name="capacity">Capacity of the segment</param>
        /// <param name="batchId">Incremental identifier of batch</param>
        public BatchingQueueSegment(int capacity, int batchId)
        {
            TurboContract.Requires(capacity > 0 && capacity <= int.MaxValue / 2, "'capacity' should be positive and less than int.MaxValue / 2");

            _array   = new T[capacity];
            _batchId = batchId;
            _markedForObservation = false;

            _reservedIndexWithFinalizationMark = 0;
            _actualCount = 0;

            _next             = null;
            _preallocatedNext = null;
        }
Exemple #19
0
        private void CreateNewInsteadOfTakenIfRequired(ref PoolElementWrapper <TElem> element, int timeout, CancellationToken token)
        {
            TurboContract.Requires(element != null, conditionString: "element != null");

            if (Volatile.Read(ref _reservedCount) < _maxElementCount && this.IsBetterAllocateNew(element.Element))
            {
                PoolElementWrapper <TElem> newElement = TryCreateNewElement(timeout, token);
                if (newElement != null)
                {
                    _elementsContainer.Release(element);
                    element = newElement;
                }
            }
        }
        /// <summary>
        /// Adds a new injection to the container
        /// </summary>
        /// <param name="key">Key</param>
        /// <param name="val">Object to add for the specified key</param>
        protected sealed override void AddInjectionInner(TKey key, object val)
        {
            TurboContract.Requires(key != null, conditionString: "key != null");

            lock (_injections)
            {
                if (_injections.ContainsKey(key))
                {
                    throw new ItemAlreadyExistsException(string.Format("InjectionContainer already contains the injection for the key ({0})", key));
                }

                _injections.Add(key, val);
            }
        }
            /// <summary>
            /// Returns estimate number of elements contained in the  ConcurrentDictionary
            /// </summary>
            /// <param name="dictionary"></param>
            /// <returns></returns>
            public static int GetEstimateCount(ConcurrentDictionary <TKey, TValue> dictionary)
            {
                TurboContract.Requires(dictionary != null, conditionString: "dictionary != null");

                var func = _getEstimateCount;

                if (func == null)
                {
                    InitGetEstimateCount();
                    func = _getEstimateCount;
                }

                return(func(dictionary));
            }
        /// <summary>
        /// Attempts to add a new association to the container
        /// </summary>
        /// <param name="key">Key</param>
        /// <param name="objType">The type of the object that will be held by the lifetime container</param>
        /// <param name="val">Factory to create a lifetime container for the sepcified 'objType'</param>
        /// <returns>True if AssociationContainer not contains lifetime container with the same key; overwise false</returns>
        protected sealed override bool TryAddAssociationInner(TKey key, Type objType, Lifetime.Factories.LifetimeFactory val)
        {
            TurboContract.Requires(key != null, conditionString: "key != null");
            TurboContract.Requires(objType != null, conditionString: "objType != null");
            TurboContract.Requires(val != null, conditionString: "val != null");

            if (_storage.ContainsKey(key))
            {
                return(false);
            }

            var lfInf = ProduceResolveInfo(key, objType, val);

            return(_storage.TryAdd(key, lfInf));
        }
Exemple #23
0
        /// <summary>
        /// Удалить элемент по индексу
        /// </summary>
        /// <param name="index">Индекс</param>
        /// <returns>Был ли удалён элемент</returns>
        public bool RemoveAt(int index)
        {
            TurboContract.Requires(index >= 0, conditionString: "index >= 0");

            lock (_syncObj)
            {
                T[] data = _data;
                if (index >= data.Length)
                {
                    return(false);
                }

                return(RemoveCore(index));
            }
        }
Exemple #24
0
        private bool ProcessTakenElement(ref PoolElementWrapper <TElem> element)
        {
            TurboContract.Requires(element != null, conditionString: "element != null");

            if (this.IsValidElement(element.Element))
            {
                return(true);
            }

            DestroyAndRemoveElement(element);
            element = null;

            Profiling.Profiler.ObjectPoolElementFaulted(this.Name, this.ElementCount);
            return(false);
        }
        // ================


        /// <summary>
        /// Переместить все элементы из локальной очереди в общую
        /// </summary>
        /// <param name="localQueue">Локальная очередь</param>
        public void MoveItemsFromLocalQueueToGlobal(ThreadPoolLocalQueue localQueue)
        {
            TurboContract.Requires(localQueue != null, conditionString: "localQueue != null");
            TurboContract.Assert(!_isDisposed, conditionString: "!_isDisposed");

            try { }
            finally
            {
                ThreadPoolWorkItem item = null;
                while (localQueue.TrySteal(out item))
                {
                    _globalQueue.ForceAdd(item);
                }
            }
        }
        /// <summary>
        /// Добавить элемент в очередь
        /// </summary>
        /// <param name="item">Элемент</param>
        /// <param name="localQueue">Локальная очередь (если есть)</param>
        /// <param name="forceGlobal">Обязательное добавление в глобальную очередь</param>
        public void Add(ThreadPoolWorkItem item, ThreadPoolLocalQueue localQueue, bool forceGlobal)
        {
            TurboContract.Requires(item != null, conditionString: "item != null");
            TurboContract.Assert(!_isDisposed, conditionString: "!_isDisposed");

            try { }
            finally
            {
                if (forceGlobal || localQueue == null || !localQueue.TryAddLocal(item))
                {
                    bool addToMainRes = _globalQueue.TryAdd(item, -1);
                    TurboContract.Assert(addToMainRes, conditionString: "addToMainRes");
                }
            }
        }
        /// <summary>
        /// Adds a new association to the container
        /// </summary>
        /// <param name="key">Key</param>
        /// <param name="val">Lifetime object container to add</param>
        protected sealed override void AddAssociationInner(TKey key, LifetimeBase val)
        {
            TurboContract.Requires(key != null, conditionString: "key != null");
            TurboContract.Requires(val != null, conditionString: "val != null");

            lock (_storage)
            {
                if (_storage.ContainsKey(key))
                {
                    throw new ItemAlreadyExistsException(string.Format("AssociationContainer already contains the association for the key ({0})", key));
                }

                _storage.Add(key, val);
            }
        }
        /// <summary>
        /// Attempts to add a new association to the container
        /// </summary>
        /// <param name="key">Key</param>
        /// <param name="val">Lifetime object container to add</param>
        /// <returns>True if AssociationContainer not contains lifetime container with the same key; overwise false</returns>
        protected bool TryAddAssociation(TKey key, LifetimeBase val)
        {
            TurboContract.Requires(key != null, conditionString: "key != null");
            TurboContract.Requires(val != null, conditionString: "val != null");
            TurboContract.Ensures(TurboContract.Result <bool>() == false || this.ContainsInner(key));

            if (!IsGoodTypeForKey(key, val.OutputType))
            {
                throw new AssociationBadKeyForTypeException(string.Format("Bad key ({0}) for the type ({1})", key, val.OutputType));
            }

            CheckContainerState(true);

            return(TryAddAssociationInner(key, val));
        }
        public bool TryAddItem(ThreadPoolWorkItem item, bool forceGlobal)
        {
            TurboContract.Requires(item != null, conditionString: "item != null");
            TurboContract.Assert(!_isDisposed, conditionString: "!_isDisposed");

            ThreadPoolLocalQueue localQueue = null;

            if (!forceGlobal)
            {
                ThreadPoolThreadLocals threadLocal = _perThreadData.Value;
                localQueue = threadLocal != null ? threadLocal.LocalQueue : null;
            }

            return(_queues.TryAdd(item, localQueue, forceGlobal));
        }
        /// <summary>
        /// Attempts to add a new injection to the container
        /// </summary>
        /// <param name="key">Key</param>
        /// <param name="val">Object to add for the specified key</param>
        /// <returns>True if the injection was added, that is InjectionContainer not contains lifetime container with the same key; overwise false</returns>
        protected sealed override bool TryAddInjectionInner(TKey key, object val)
        {
            TurboContract.Requires(key != null, conditionString: "key != null");

            lock (_injections)
            {
                if (_injections.ContainsKey(key))
                {
                    return(false);
                }

                _injections.Add(key, val);
            }

            return(true);
        }