/// <summary> /// Attempts to generate dynamic method to run in action in ExceutionContext /// </summary> /// <returns>Delegate for generated method</returns> private static RunInContextDelegate TryCreateRunInContextMethod() { var runContextMethodCandidates = typeof(ExecutionContext).GetMethods(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic).Where(o => o.Name == "RunInternal" && o.GetParameters().Length == 4).ToList(); if (runContextMethodCandidates.Count != 1) { #if NET45 || NET46 TurboContract.Assert(false, "ExecutionContextHelper.TryCreateRunInContextMethod should be successful for known runtimes"); #endif return(null); } var method = new DynamicMethod("ExecutionContext_Run_Internal_" + Guid.NewGuid().ToString("N"), typeof(void), new Type[] { typeof(ExecutionContext), typeof(ContextCallback), typeof(object), typeof(bool) }, true); var ilGen = method.GetILGenerator(); ilGen.Emit(OpCodes.Ldarg_0); ilGen.Emit(OpCodes.Ldarg_1); ilGen.Emit(OpCodes.Ldarg_2); ilGen.Emit(OpCodes.Ldarg_3); ilGen.Emit(OpCodes.Call, runContextMethodCandidates[0]); ilGen.Emit(OpCodes.Ret); return((RunInContextDelegate)method.CreateDelegate(typeof(RunInContextDelegate))); }
/// <summary>Code contracts</summary> public bool TryGetAssociation(T key, out LifetimeBase val) { TurboContract.Ensures((TurboContract.Result <bool>() == true && TurboContract.ValueAtReturn <LifetimeBase>(out val) != null) || (TurboContract.Result <bool>() == false && TurboContract.ValueAtReturn <LifetimeBase>(out val) == null)); throw new NotImplementedException(); }
/// <summary> /// Compares two elements to choose the best one (a > b => result > 0; a == b => result == 0; a < b => result < 0) /// </summary> /// <param name="a">First element to compare</param> /// <param name="b">Second element to compare</param> /// <param name="stopHere">Flag that indicates that the element '<paramref name="a"/>' is sufficient and scanning can be stopped</param> /// <returns>Comparison result</returns> public override int Compare(PoolElementWrapper <TElem> a, PoolElementWrapper <TElem> b, out bool stopHere) { TurboContract.Requires(a != null, conditionString: "a != null"); TurboContract.Requires(b != null, conditionString: "b != null"); return(_objectPool.CompareElements(a.Element, b.Element, out stopHere)); }
// ===================== /// <summary> /// Попробовать выполнить похищение элемента из соседних локальных очередей /// </summary> /// <param name="localQueue">Локальная очередь текущего потока</param> /// <param name="otherLocalQueues">Разреженный массив локальных очередей других потоков</param> /// <param name="item">Выбранный элемент</param> /// <returns>Удалось ли сделать выборку</returns> private bool TryTakeFromOtherLocalQueues(ThreadPoolLocalQueue localQueue, ThreadPoolLocalQueue[] otherLocalQueues, out ThreadPoolWorkItem item) { TurboContract.Requires(otherLocalQueues != null, conditionString: "otherLocalQueues != null"); TurboContract.Ensures(TurboContract.Result <bool>() == false || TurboContract.ValueAtReturn(out item) != null); bool result = false; item = null; try { } finally { int length = otherLocalQueues.Length; int index = Interlocked.Increment(ref _stealIndex) & int.MaxValue; for (int i = 0; i < length; i++, index++) { var otherQueue = Volatile.Read(ref otherLocalQueues[index % length]); if (otherQueue != null && otherQueue != localQueue && otherQueue.TrySteal(out item)) { result = true; break; } } } return(result); }
/// <summary> /// Добавить локальную оередь в массив /// </summary> /// <param name="localQueue">Локальная очередь потока</param> public void AddLocalQueue(ThreadPoolLocalQueue localQueue) { TurboContract.Requires(localQueue != null, conditionString: "localQueue != null"); TurboContract.Ensures(_localQueues.Contains(localQueue)); TurboContract.Assert(!_isDisposed, conditionString: "!_isDisposed"); lock (_syncObj) { var arrayCopy = _localQueues; TurboContract.Assert(arrayCopy != null, conditionString: "arrayCopy != null"); for (int i = 0; i < arrayCopy.Length; i++) { TurboContract.Assert(Volatile.Read(ref arrayCopy[i]) != localQueue, conditionString: "Volatile.Read(ref arrayCopy[i]) != localQueue"); if (Volatile.Read(ref arrayCopy[i]) == null) { Volatile.Write(ref arrayCopy[i], localQueue); return; } } int oldLength = arrayCopy.Length; Array.Resize(ref arrayCopy, oldLength + 4); Volatile.Write(ref arrayCopy[oldLength], localQueue); _localQueues = arrayCopy; } }
public int RegisterAndMakeSuggestionTest(int workThreadCount, int executedTaskCount, int elapsedMs) { TurboContract.Requires(workThreadCount >= 0, conditionString: "workThreadCount >= 0"); RegisterExecution(executedTaskCount); RegisterMeasure(workThreadCount, _isPerfMeasureThreadWork, elapsedMs); return(MakeSuggestion(true, false)); }
/// <summary> /// Attempts to generates dynamic method for RegisterWithoutEC /// </summary> /// <returns>Delegate for generated method if successful, otherwise null</returns> private static RegisterWithoutECDelegate TryGenerateRegisterWithoutECMethod() { var registerMethodCandidates = typeof(CancellationToken).GetMethods(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).Where(o => o.Name == "Register" && o.GetParameters().Length == 4).ToList(); if (registerMethodCandidates.Count != 1) { TurboContract.Assert(false, "CancellationTokenHelper.TryCreateRegisterWithoutECMethod should be successful for known runtimes"); return(null); } var method = new DynamicMethod("CancellationToken_RegisterWithoutEC_" + Guid.NewGuid().ToString("N"), typeof(CancellationTokenRegistration), new Type[] { typeof(CancellationToken).MakeByRefType(), typeof(Action <object>), typeof(object) }, true); var ilGen = method.GetILGenerator(); ilGen.Emit(OpCodes.Ldarg_0); ilGen.Emit(OpCodes.Ldarg_1); ilGen.Emit(OpCodes.Ldarg_2); ilGen.Emit(OpCodes.Ldc_I4_0); ilGen.Emit(OpCodes.Ldc_I4_0); ilGen.Emit(OpCodes.Call, registerMethodCandidates[0]); ilGen.Emit(OpCodes.Ret); return((RegisterWithoutECDelegate)method.CreateDelegate(typeof(RegisterWithoutECDelegate))); }
/// <summary> /// Выполнить переход в состояние /// </summary> /// <param name="description">Описание причин перехода</param> /// <param name="state">Новое состояние</param> private void GoToState(string description, ExecutionThroughoutTrackerUpSmartDownCorrectionState state) { if (!CanChangeState(_state, state)) { throw new InvalidOperationException("Invalid state change from " + _state.ToString() + " to " + state.ToString()); } //Console.WriteLine(description + ". State = " + _state.ToString() + ", NewState = " + state.ToString()); if (_state != state) { _state = state; _enterStateTimeStamp = GetTimestamp(); _enterStateThroughoutData = this.GetCurrentMeasure(); _stateMeasureCount = 0; _tryIncreaseBlinkCount = 0; _tryDecreaseBlinkCount = 0; _tryDecreaseInitialThreadCount = -1; _optimalStateAverageThroughout = -1; TurboContract.Assert(_isPerfMeasureThreadWork == false, conditionString: "_isPerfMeasureThreadWork == false"); } }
/// <summary> /// Конструктор IndexedStackElementStorage /// </summary> /// <param name="dataArray">Массив данных</param> public IndexedStackElementStorage(SparceArrayStorage <PoolElementWrapper <T> > dataArray) { TurboContract.Requires(dataArray != null, conditionString: "dataArray != null"); _headIndexOp = Repack(NoElementHeadIndex, 1); _dataArray = dataArray; }
/// <summary> /// Runs the action inside closure /// </summary> /// <param name="closure">Closure object</param> public static void Run(object closure) { var unwrapClosure = (ParameterizedClosure <TState>)closure; TurboContract.Assert(unwrapClosure != null, conditionString: "unwrapClosure != null"); unwrapClosure.Action(unwrapClosure.State); }
public T Resolve <T>() { var life = this.GetAssociation(typeof(T)); TurboContract.Assert(life != null, conditionString: "life != null"); return((T)life.GetInstance(_resolver)); }
public bool TryResolve(T key, out object val) { TurboContract.Requires(key != null, conditionString: "key != null"); TurboContract.Ensures(TurboContract.Result <bool>() == true || (TurboContract.Result <bool>() == false && TurboContract.ValueAtReturn <object>(out val) == null)); throw new NotImplementedException(); }
/// <summary> /// Creates TransformedReadOnlyListWrapper from the current list /// </summary> /// <typeparam name="TOut">Type of the elements of the newly created TransformedReadOnlyListWrapper</typeparam> /// <param name="selector">Element conversion delegate</param> /// <returns>Created TransformedReadOnlyListWrapper</returns> public TransformedReadOnlyListWrapper <T, TOut> AsTransformedReadOnlyList <TOut>(Func <T, TOut> selector) { TurboContract.Requires(selector != null, conditionString: "selector != null"); TurboContract.Ensures(TurboContract.Result <TransformedReadOnlyListWrapper <T, TOut> >() != null); return(new TransformedReadOnlyListWrapper <T, TOut>(_list, selector)); }
/// <summary> /// Attempts to generate dynamic method to capture ExecutionContext without SynchronizationContext /// </summary> /// <returns>Delegate for generated method</returns> private static CaptureContextDelegate TryCreateCaptureContextMethod() { var execContextMethodCandidates = typeof(ExecutionContext).GetMethods(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic).Where(o => o.Name == "Capture" && o.GetParameters().Length == 2).ToList(); if (execContextMethodCandidates.Count != 1) { #if NET45 || NET46 TurboContract.Assert(false, "ExecutionContextHelper.TryCreateCaptureContextMethod should be successful for known runtimes"); #endif return(null); } var method = new DynamicMethod("ExecutionContext_Capture_Internal_" + Guid.NewGuid().ToString("N"), typeof(ExecutionContext), Type.EmptyTypes, true); var ilGen = method.GetILGenerator(); var stackMark = ilGen.DeclareLocal(typeof(int)); ilGen.Emit(OpCodes.Ldc_I4_1); ilGen.Emit(OpCodes.Stloc_0); ilGen.Emit(OpCodes.Ldloca_S, stackMark); ilGen.Emit(OpCodes.Ldc_I4_3); ilGen.Emit(OpCodes.Call, execContextMethodCandidates[0]); ilGen.Emit(OpCodes.Ret); return((CaptureContextDelegate)method.CreateDelegate(typeof(CaptureContextDelegate))); }
/// <summary> /// Конструктор ExecutionThroughoutTrackerUpHardDownCorrection /// </summary> /// <param name="maxThreadCount">Максимальное число потоков</param> /// <param name="reasonableThreadCount">Базовое число потоков</param> public ExecutionThroughoutTrackerUpHardDownCorrection(int maxThreadCount, int reasonableThreadCount) { TurboContract.Requires(maxThreadCount > 0, conditionString: "maxThreadCount > 0"); TurboContract.Requires(reasonableThreadCount > 0, conditionString: "reasonableThreadCount > 0"); TurboContract.Requires(maxThreadCount >= reasonableThreadCount, conditionString: "maxThreadCount >= reasonableThreadCount"); _maxThreadCount = maxThreadCount; _reasonableThreadCount = reasonableThreadCount; _executedTasks = 0; _lastTimeStamp = GetTimestamp(); _data = new ThroughoutData[EstimationDataLength]; _nextDataIndex = 0; _state = ExecutionThroughoutTrackerUpHardDownCorrectionState.FindBestDirection; _enterStateTimeStamp = GetTimestamp(); _enterStateThroughoutData = new ThroughoutData(); _stateMeasureCount = 0; _findBestDirectionBlinkCount = 0; _optimalStateAverageThroughout = -1; _isPerfMeasureThreadWork = false; }
/// <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 sealed override bool TryAddAssociationInner(TKey key, Lifetime.LifetimeBase val) { TurboContract.Requires(key != null, conditionString: "key != null"); TurboContract.Requires(val != null, conditionString: "val != null"); return(_storage.TryAdd(key, val)); }
/// <summary> /// Зарегистрировать измерение и сделать предположение по улучшению производительности /// </summary> /// <param name="workThreadCount">Текущее число потоков</param> /// <param name="needAction">Нужно ли что-то делать</param> /// <param name="isCriticalCondition">Критические ли условия</param> /// <returns>На сколько надо изменить число потоков</returns> public int RegisterAndMakeSuggestion(int workThreadCount, bool needAction, bool isCriticalCondition) { TurboContract.Requires(workThreadCount >= 0, conditionString: "workThreadCount >= 0"); RegisterMeasure(workThreadCount, _isPerfMeasureThreadWork); return(MakeSuggestion(needAction, isCriticalCondition)); }
/// <summary> /// Returns rented element back to the object pool /// </summary> public void Dispose() { var wrapperCopy = _elementWrapper; var sourcePool = _sourcePool; _elementWrapper = null; _sourcePool = null; TurboContract.Assert((wrapperCopy == null && sourcePool == null) || (wrapperCopy != null && sourcePool != null), conditionString: "(wrapperCopy == null && sourcePool == null) || (wrapperCopy != null && sourcePool != null)"); if (wrapperCopy != null && sourcePool != null) { sourcePool.ReleaseElement(wrapperCopy); Profiling.Profiler.ObjectPoolElementRentedTime(wrapperCopy.SourcePoolName, this.StopActiveTime()); } #if DEBUG if (wrapperCopy != null) { wrapperCopy.UpdateStatOnRelease(); } GC.SuppressFinalize(this); #endif }
/// <summary> /// Releases element back to the pool. Normally should be called from <see cref="RentedElementMonitor{TElem}"/> /// </summary> /// <param name="element">Element wrapper to be released</param> protected internal sealed override void ReleaseElement(PoolElementWrapper <TElem> element) { TurboContract.Requires(element != null, conditionString: "element != null"); if (!element.IsBusy) { throw new InvalidOperationException("Trying to release same element several times in Pool: " + this.Name); } if (_disposeCancellation.IsCancellationRequested) { DestroyAndRemoveElement(element); } else { _elementsContainer.Release(element); if (_disposeCancellation.IsCancellationRequested) { TakeDestroyAndRemoveElement(); } } if (_disposeCancellation.IsCancellationRequested && _elementsContainer.Count == 0) { _stoppedEvent.Set(); } Profiling.Profiler.ObjectPoolElementReleased(this.Name, this.RentedElementCount); }
public CallbackItem(ManagementThreadControllerCallback callback) { TurboContract.Requires(callback != null, conditionString: "callback != null"); _callback = callback; _startTimeMs = TimeoutHelper.GetTimestamp(); }
public object CreateInstance(IInjectionResolver resolver) { TurboContract.Requires(resolver != null, conditionString: "resolver != null"); TurboContract.Ensures(TurboContract.Result <object>() != null); throw new NotImplementedException(); }
/// <summary> /// Cleans-up resources /// </summary> /// <param name="isUserCall">Is it called explicitly by user (False - from finalizer)</param> protected override void Dispose(bool isUserCall) { if (!this.IsStopRequestedOrStopped) { TurboContract.Assert(isUserCall, "QueueAsyncProcessor destructor: Better to dispose by user"); if (isUserCall) { StopProcessor(true, false, true); } QueueAsyncProcessorState prevState; ChangeStateSafe(QueueAsyncProcessorState.StopRequested, out prevState); ChangeStateSafe(QueueAsyncProcessorState.Stopped, out prevState); if (_stopRequestedCancelation != null) { _stopRequestedCancelation.Cancel(); } if (_stoppedCancelation != null) { _stoppedCancelation.Cancel(); } this.DisposeQueue(); if (!isUserCall) { Profiling.Profiler.QueueAsyncProcessorDisposed(this.Name, true); } } base.Dispose(isUserCall); }
/// <summary> /// Запросить временное расширение вместимости /// </summary> /// <param name="extensionVal">Величиная расширения</param> public void ExtendGlobalQueueCapacity(int extensionVal) { TurboContract.Requires(extensionVal >= 0, conditionString: "extensionVal >= 0"); TurboContract.Assert(!_isDisposed, conditionString: "!_isDisposed"); _globalQueue.RequestCapacityExtension(extensionVal); }
/// <summary> /// Waits until predicate estimates to true or cancellation received or dispose happened /// </summary> private bool WaitUntilPredicate <TState>(WaitPredicate <TState> predicate, TState state, uint startTime, int timeout, CancellationToken token) { TurboContract.Assert(predicate != null, conditionString: "predicate != null"); int remainingWaitMilliseconds = Timeout.Infinite; while (true) { if (token.IsCancellationRequested || _isDisposed) { return(false); } if (timeout != Timeout.Infinite) { remainingWaitMilliseconds = TimeoutHelper.UpdateTimeout(startTime, timeout); if (remainingWaitMilliseconds <= 0) { return(false); } } if (!Monitor.Wait(this, remainingWaitMilliseconds)) { return(false); } if (predicate.Invoke(state)) { return(true); } } }
/// <summary> /// Cancellation handler for CancellationToken /// </summary> /// <param name="obj">ConditionVariable object</param> private static void CancellationTokenCanceledEventHandler(object obj) { MonitorObject monitorObject = obj as MonitorObject; TurboContract.Assert(monitorObject != null, conditionString: "monitorObject != null"); monitorObject.PulseAll(); }
/// <summary> /// Cancellation handler for CancellationToken /// </summary> /// <param name="obj">ConditionVariable object</param> private static void CancellationTokenCanceledEventHandler(object obj) { SignalWaiter signalWaiter = obj as SignalWaiter; TurboContract.Assert(signalWaiter != null, conditionString: "signalWaiter != null"); signalWaiter.SignalAll(); }
public override int Compare(PoolElementWrapper <T> a, PoolElementWrapper <T> b, out bool stopHere) { TurboContract.Requires(a != null, conditionString: "a != null"); TurboContract.Requires(b != null, conditionString: "b != null"); throw new NotImplementedException(); }
/// <summary> /// SignalWaiter constructor /// </summary> /// <param name="originalEvents">The sequence of events that emit signals for the current waiter</param> /// <param name="signalMode">Signaling mode</param> public SignalWaiter(IEnumerable <SignalEvent> originalEvents, SignalMode signalMode) { if (originalEvents == null) { throw new ArgumentNullException(nameof(originalEvents)); } TurboContract.Assert(Enum.IsDefined(typeof(SignalMode), signalMode), conditionString: "Enum.IsDefined(typeof(SignalMode), signalMode)"); _originalEvent = null; _signalMode = signalMode; _isDisposed = false; List <WeakReference <SignalEvent> > originalEventsTmp = new List <WeakReference <SignalEvent> >(); foreach (var ev in originalEvents) { if (ev == null) { throw new ArgumentNullException(nameof(originalEvents), "One of the signal events is null"); } originalEventsTmp.Add(new WeakReference <SignalEvent>(ev)); ev.Subscribe(SignalHandler); } _originalEventList = originalEventsTmp.ToArray(); }
/// <summary> /// Захватить лучший элемент из доступных /// </summary> /// <param name="element">Захваченный элемент</param> /// <returns>Удалось ли захватить</returns> private bool TryTakeBest(out PoolElementWrapper <T> element) { TurboContract.Ensures((TurboContract.Result <bool>() == false && TurboContract.ValueAtReturn(out element) == null) || (TurboContract.Result <bool>() == true && TurboContract.ValueAtReturn(out element) != null && TurboContract.ValueAtReturn(out element).IsBusy)); PoolElementWrapper <T> b1, b2, b3; PoolElementWrapper <T> earlyStopResult = FindBest3WithStopping(out b1, out b2, out b3); if (earlyStopResult != null) { TurboContract.Assert(earlyStopResult.IsBusy, conditionString: "earlyStopResult.IsBusy"); element = earlyStopResult; return(true); } if (b1 != null && b1.TryMakeBusyAtomic() && !b1.IsRemoved) { element = b1; return(true); } if (b2 != null && b2.TryMakeBusyAtomic() && !b2.IsRemoved) { element = b2; return(true); } if (b3 != null && b3.TryMakeBusyAtomic() && !b3.IsRemoved) { element = b3; return(true); } element = null; return(false); }
internal void ExitClient(bool isBackground) { SpinWait sw = new SpinWait(); while (true) { int combinedState = _combinedState; int newValue = combinedState - 1; TurboContract.Assert(combinedState >= 0, conditionString: "combinedState >= 0"); TurboContract.Assert((!IsMainGateOpened(combinedState) && isBackground) || (!IsBackgroundGateOpened(combinedState) && !isBackground), "Can exit only if specified gate opened"); TurboContract.Assert(!IsBackgroundGateOpened(combinedState) || !IsMainGateOpened(combinedState), "Two gates can't be opened at the same time"); TurboContract.Assert(GetClientCount(combinedState) > 0, "Client number should be positive"); TurboContract.Assert(IsAllowBackground(combinedState) || !IsBackgroundGateOpened(combinedState), "When background is not allowed, background gate should be closed"); if (GetClientCount(newValue) == 0) // zero number of clients => can switch gates { newValue = UpdateZeroClientCountState(newValue); } if (Interlocked.CompareExchange(ref _combinedState, newValue, combinedState) == combinedState) { if (GetGatesState(combinedState) != GetGatesState(newValue)) { SwapGatesAtomic(newValue); } return; } sw.SpinOnce(); } }