public LocalMessage(TPayload payload, bool ownsPayload) { payload.EnsureNotNull(nameof(payload)); // _localCreationTimestamp = DateTimeOffset.Now; _payload = payload.ToValueHolder(ownsValue: ownsPayload); }
internal P_DefaultHolder(IVh <CompiledLambdaExpressionCache> holder) { holder.EnsureNotNull(nameof(holder)); // Holder = holder; Value = holder.Value; }
protected override void Dispose(bool explicitDispose) { if (explicitDispose) { _newDependencyInstancesDisposeRegistry?.Dispose(); // _runningResolutionsSpinLock?.EnterAndExitLock(); _runningResolutionsUniqueness?.Clear(); _runningResolutionsSequence?.Clear(); // _resolutionModelLazy?.Dispose(); // _exporter?.Dispose(); // _outerScopeGetter?.Dispose(); } _newDependencyInstancesDisposeRegistry = null; _runningResolutionsUniqueness = null; _runningResolutionsSequence = null; _runningResolutionsSpinLock = null; _resolutionModelLazy = null; _exporter = null; _outerScopeGetter = null; _serviceProviderApi = null; _owner = null; // base.Dispose(explicitDispose); }
public DisposableLazy(IVh <T> valueStore) { valueStore.EnsureNotNull(nameof(valueStore)); // _identity = null; _factory = null; _valueHolder = valueStore; }
/// <summary> /// Инициализирует новый экземпляр типа <see cref="StreamInfo"/>. /// </summary> /// <param name="stream">Поток.</param> /// <param name="contentMediaType"> /// Медиа-тип содержимого потока. /// <para>По умолчанию (в том числе, когда <paramref name="contentMediaType"/> равен null) используется медиа-тип <see cref="MediaTypeNameUtilities.AppOctetStream"/>.</para> /// </param> public StreamInfo(IVh <Stream> stream, string contentMediaType = null) { stream.Arg(nameof(stream)).EnsureSelfAndValueNotNull(); contentMediaType.Arg(nameof(contentMediaType)).EnsureHasMaxLength(maxLength: MediaTypeNameUtilities.MediaTypeNameDefaultMaxLength).EnsureNotEmptyOrWhiteSpace(); // _streamStore = stream; _contentMediaType = contentMediaType ?? MediaTypeNameUtilities.AppOctetStream; }
public ServiceProviderHandler(ArgumentUtilitiesHandle <IServiceProvider> serviceProvider) { serviceProvider.EnsureNotNull(); // _serviceProvider = serviceProvider.Value; _serviceScope = null; _hasServiceScope = false; }
public DependencyScope(IOuterDependencyScopeGetter outerScopeGetter, IDependencyExporter exporter, bool ownsExporter = default, bool prohibitNewInstanceRequest = default, object owner = default) { outerScopeGetter.EnsureNotNull(nameof(outerScopeGetter)); // _outerScopeGetter = outerScopeGetter.ToValueHolder(ownsValue: false); _prohibitNewInstanceRequest = prohibitNewInstanceRequest; P_CtorInitializer(exporter: exporter, ownsDependencyExporter: ownsExporter, owner: owner); }
public DisposableLazy(Func <T> factory, bool ownsValue) { factory.EnsureNotNull(nameof(factory)); // _identity = new object(); _factory = factory; _ownsValue = ownsValue; _valueHolder = null; }
protected override void Dispose(bool explicitDispose) { if (explicitDispose) { _embeddedMetadata?.Dispose(); } _embeddedMetadata = null; // base.Dispose(explicitDispose); }
static Task P_DefaultRelease(IVh <T> instance) { try { instance?.Dispose(); return(TaskUtilities.FromVoidResult()); } catch (Exception exception) { return(TaskUtilities.FromError(exception)); } }
public ServiceProviderHandler(ArgumentUtilitiesHandle <IServiceScope> serviceScope, bool ownsServiceScope = default) { var locServiceScope = serviceScope.EnsureNotNull().Value; var locServiceProvider = locServiceScope.ServiceProvider.ArgProp($"{nameof(serviceScope)}.{nameof(serviceScope.Value.ServiceProvider)}").EnsureNotNull().Value; // _serviceProvider = locServiceProvider; _serviceScope = locServiceScope.ToValueHolder(ownsValue: ownsServiceScope); _hasServiceScope = true; }
protected override void Dispose(bool explicitDispose) { if (explicitDispose) { _payload?.Dispose(); } _payload = null; // base.Dispose(explicitDispose); }
protected override void Dispose(bool explicitDispose) { if (explicitDispose) { _streamStore?.Dispose(); } _streamStore = null; _contentMediaType = null; // base.Dispose(explicitDispose); }
protected override void Dispose(bool explicitDispose) { if (explicitDispose) { _realHolder?.Dispose(); _disposeRegistry?.Dispose(); } _realHolder = null; _disposeRegistry = null; // base.Dispose(explicitDispose); }
protected override void Dispose(bool explicitDispose) { if (explicitDispose) { _sharedInstanceInitializationLock?.Dispose(); _sharedInstanceStore?.Dispose(); } _sharedInstanceInitializationLock = null; _sharedInstanceStore = null; // base.Dispose(explicitDispose); }
public DependencyScope(ArgumentUtilitiesHandle <IServiceProviderHandler> outerServiceProvider, bool ownsOuterServiceProvider = default) { outerServiceProvider.EnsureNotNull(); // _outerScopeGetter = new DefaultOuterDependencyScopeGetter(outerScope: null).ToValueHolder(ownsValue: true); _prohibitNewInstanceRequest = false; P_CtorInitializer( exporter: new DefaultDependencyExporter(handler: outerServiceProvider.Value, ownsHandler: ownsOuterServiceProvider), ownsDependencyExporter: true, outerServiceProvider: outerServiceProvider.Value.ServiceProvider, owner: null); }
public EmbeddedMetadataTreeElement(IMetadataTreeNode node, IMetadata embeddedMetadata, bool ownsEmbeddedMetadata, bool linkEmbeddedMetadata = false, ReadOnlyStateTag readOnlyState = null) : base(node: node, readOnlyState: readOnlyState) { // embeddedMetadata.EnsureNotNull(nameof(embeddedMetadata)); // _embeddedMetadata = embeddedMetadata.ToValueHolder(ownsEmbeddedMetadata); // if (linkEmbeddedMetadata) { SetMetadata(new Link <IMetadataTreeElement, IVh <IMetadata> >(this, embeddedMetadata.ToValueHolder())); } }
protected override void Dispose(bool explicitDispose) { if (explicitDispose) { _specs?.Dispose(); _involvedHandlerSpinLock?.EnterAndExitLock(); _involvedHandlerChain?.Clear(); _involvedHandlerCounters?.Clear(); } _involvedHandlerCounters = null; _involvedHandlerChain = null; _involvedHandlerSpinLock = null; _scope = null; _specs = null; // base.Dispose(explicitDispose); }
public DependencyResolutionContext(IDependencyScope scope, IDependencyResolutionSpecs specs, bool ownsSpecs = default, bool?isAdvancedLoggingEnabled = default) { scope.EnsureNotNull(nameof(scope)); specs.EnsureNotNull(nameof(specs)); // _sequentialId = DependencyUtilities.NextResolutionContextSequentialId(); _scope = scope; _specs = specs.ToValueHolder(ownsValue: ownsSpecs); _involvedHandlerCounters = new Dictionary <IDependencyHandler2, int>(comparer: ReferenceEqualityComparer <IDependencyHandler2> .Instance); _involvedHandlerChain = new List <IDependencyHandler2>(); _involvedHandlerSpinLock = new PrimitiveSpinLock(); // var resolutionSettings = DependencyUtilities.DefaultResolutionSettings; _usageCountLimitPerHandler = resolutionSettings.UsageCountLimitPerHandler; _isAdvancedLoggingEnabled = isAdvancedLoggingEnabled ?? resolutionSettings.IsAdvancedLoggingEnabled; }
void P_CtorInitializer(IDependencyExporter exporter, bool ownsDependencyExporter = default, IServiceProvider outerServiceProvider = default, object owner = default) { exporter.EnsureNotNull(nameof(exporter)); // _exporter = exporter.ToValueHolder(ownsDependencyExporter); _owner = owner; // _resolutionModelLazy = new DisposableLazy <IDependencyResolutionModel <DependencyScope> >( factory: () => new DependencyResolutionModel <DependencyScope>(scope: this, handlerChainSource: ReadDA(ref _exporter, considerDisposeRequest: true).Value.ExportDependencies()), ownsValue: true); // _newDependencyInstancesDisposeRegistry = new DisposeRegistry(); // _runningResolutionsSpinLock = new PrimitiveSpinLock(); _runningResolutionsUniqueness = new HashSet <IDependencyResolutionContext>(comparer: ReferenceEqualityComparer <IDependencyResolutionContext> .Instance); _runningResolutionsSequence = new List <IDependencyResolutionContext>(); // _serviceProviderApi = outerServiceProvider ?? new P_ServiceProviderApi(scope: this); }
public DependencyScope(IDependencyScope outerScope, IDependencyExporter exporter, bool ownsExporter = default, bool prohibitNewInstanceRequest = default, object owner = default) { _outerScopeGetter = new DefaultOuterDependencyScopeGetter(outerScope: outerScope).ToValueHolder(ownsValue: true); _prohibitNewInstanceRequest = prohibitNewInstanceRequest; P_CtorInitializer(exporter: exporter, ownsDependencyExporter: ownsExporter, owner: owner); }
public static TValue GetOrDefault <TValue>(this IVh <TValue> vs) => vs is null ? default : vs.ValueDisposeTolerant;
// TODO: Put strings into the resources. // public Task <IVh <T> > AcquireAsync(IContext context = default) { try { var existingTask = itrlck.Get(ref _acquireTask); var ct = context?.Ct() ?? CancellationToken.None; if (existingTask is null) { var newTaskProxy = default(TaskCompletionSource <IVh <T> >); try { newTaskProxy = new TaskCompletionSource <IVh <T> >(creationOptions: TaskCreationOptions.RunContinuationsAsynchronously); if (itrlck.UpdateIfNullBool(location: ref _acquireTask, value: newTaskProxy.Task, current: out existingTask)) { if (itrlck.Get(ref _releaseTask) is null) { existingTask .ContinueWith( continuationAction: t => itrlck.SetNull(location: ref _acquireTask, comparand: t), continuationOptions: TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.NotOnRanToCompletion); doAcquireAsync(locContext: context).ContinueWithTryApplyResultTo(taskProxy: newTaskProxy); } else { newTaskProxy.TrySetException(exception: new EonException(message: $"Invalid acquisition attempt. Release operation has been attempted already.{Environment.NewLine}\tLease ID:{_id.FmtStr().GNLI2()}")); } return(existingTask); } else { return(existingTask.WaitResultAsync(ct: ct)); } } catch (Exception exception) { if (newTaskProxy?.TrySetException(exception) == true) { return(newTaskProxy.Task); } else { throw; } } finally { if (!ReferenceEquals(newTaskProxy.Task, existingTask)) { newTaskProxy.TrySetCanceled(); } } } else { return(existingTask.WaitResultAsync(ct: ct)); } } catch (Exception exception) { return(TaskUtilities.FromError <IVh <T> >(exception)); } // async Task <IVh <T> > doAcquireAsync(IContext locContext) { var locAcquire = itrlck.Get(ref _acquire); var locRelease = itrlck.Get(ref _release); if (itrlck.Get(ref _releaseTask) is null) { try { IVh <T> locAcquired = default; try { locAcquired = await locAcquire(arg : locContext).ConfigureAwait(false); if (locAcquired is null) { throw new EonException(message: $"Instance acquisition method has returned invalid value '{locAcquired.FmtStr().G()}'.{Environment.NewLine}\tLease ID:{_id.FmtStr().GNLI2()}"); } _acquireDateTime = DateTimeOffset.Now; _logger ?.LogDebug( eventId: LeasableEventIds.LeaseStart, message: $"Lease started.{Environment.NewLine}\tLease ID:{Environment.NewLine}\t\t{{lease_id}}{Environment.NewLine}\tCorrelation ID:{Environment.NewLine}\t\t{{correlation_id}}", args: new object[] { _id.ToString(), locContext?.FullCorrelationId.ToString() }); return(locAcquired); } catch (Exception locException) { if (!(locAcquired is null)) { try { await locRelease(arg : locAcquired).ConfigureAwait(false); } catch (Exception locSecondException) { throw new AggregateException(locException, locSecondException); } } throw; } } catch (Exception locException) { try { _logger ?.LogWarning( eventId: LeasableEventIds.LeaseStart, exception: locException, message: $"Lease start error.{Environment.NewLine}\tLease ID:{Environment.NewLine}\t\t{{lease_id}}{Environment.NewLine}\tCorrelation ID:{Environment.NewLine}\t\t{{correlation_id}}", args: new object[] { _id.ToString(), locContext?.FullCorrelationId.ToString() }); } catch (Exception locSecondException) { throw new AggregateException(locException, locSecondException); } throw; } } else { throw new EonException(message: $"Invalid lease start attempt. Lease end has been attempted already.{Environment.NewLine}\tLease ID:{_id.FmtStr().GNLI2()}"); } } }
protected virtual void BuildDependencyExporter(IOuterDependencyScopeGetter outerScopeGetter, out IVh <IDependencyExporter> exporter) => exporter = new P_DelegatedDependencyExporter(export: LocalDependencies).ToValueHolder(ownsValue: true);
public DisposableLazy(T value) { _identity = null; _factory = null; _valueHolder = value.ToValueHolder(ownsValue: false); }
internal P_HolderWithDisposeRegistry(T value, IEnumerable <IDisposable> disposables) { _realHolder = value.ToValueHolder(ownsValue: true); _disposeRegistry = new DisposeRegistry(disposables: disposables); }
protected virtual void BuildDependencyExporter(IOuterDependencyScopeGetter outerScope, out IVh <IDependencyExporter> exporter) { outerScope.EnsureNotNull(nameof(outerScope)); // exporter = outerScope.GetOuterScope().ResolveDependency <IMetadataDependencyExporterBuilder>(ensureResolution: true).BuildFor(metadata: this); }
public abstract void Invoke(StatefulSynchronizationContext <TCtxState> ctx, IVh <TCtxState> ctxState);
protected override void BuildDependencyExporter(IOuterDependencyScopeGetter outerScope, out IVh <IDependencyExporter> exporter) => ReadDA(ref _metadata).BuildDependencyExporter(outerScope: outerScope, out exporter);
static void P_Loop(object state) { var startState = state.EnsureNotNull(nameof(state)).EnsureOfType <P_LoopStartState>().Value; // var ctx = startState.Context; IUnhandledExceptionObserver unhandledExceptionObserver; IRunControl runControl; CancellationToken ct; Func <CancellationToken, IVh <TCtxState> > stateFactory; ManualResetEventSlim awakeLoopEvent; Queue <P_InvokeItemBase> queue; PrimitiveSpinLock queueSpinLock; try { unhandledExceptionObserver = ctx.P_UnhandledExceptionObserver; runControl = ctx.RunControl; ct = ctx.P_Ct; stateFactory = ctx.P_StateFactory; awakeLoopEvent = ctx.P_AwakeLoopEvent; queue = ctx.P_InvokeQueue; queueSpinLock = ctx.P_InvokeQueueSpinLock; } catch (ObjectDisposedException) { return; } var bypassUnhandledExceptionObserver = false; try { Exception caughtException1 = default; try { ctx.P_IsLoopAlive = true; startState.LoopStartedEvent.Set(); // IVh <TCtxState> ctxState = default; Exception caughtException2 = default; try { // Создание объекта состояния контекста. // try { ctxState = stateFactory(arg: ct); } catch (Exception exception) { ctxState = new Vh <TCtxState>(exception: exception); } // Цикл обработки очереди. // for (; ;) { if (runControl.HasStopRequested || ct.IsCancellationRequested) { break; } // P_InvokeItemBase queueItem = default; try { queueItem = queueSpinLock.Invoke(() => queue.Count > 0 ? queue.Dequeue() : null); if (!(queueItem is null)) { if (queueItem.IsInvokeCompleted) { continue; } else { try { itrlck.Set(ref ctx._currentInvoke, queueItem); queueItem.Invoke(ctx: ctx, ctxState: ctxState); } catch (Exception exception) { if (bypassUnhandledExceptionObserver) { throw; } else { bool isExceptionObserved; try { isExceptionObserved = unhandledExceptionObserver.ObserveException(exception: exception, component: queueItem); } catch (Exception secondException) { bypassUnhandledExceptionObserver = true; throw new AggregateException(exception, secondException); } if (!isExceptionObserved) { bypassUnhandledExceptionObserver = true; throw; } } } } finally { itrlck.SetNull(ref ctx._currentInvoke, queueItem); } continue; } } catch (Exception exception) { try { queueItem.TrySetInvokeResultAsCanceled(); } catch (Exception secondException) { throw new AggregateException(exception, secondException); } throw; } // Ожидание. // if (awakeLoopEvent.IsSet) { awakeLoopEvent.Reset(); } else { awakeLoopEvent.Wait(millisecondsTimeout: 937); } } } catch (Exception exception) { caughtException2 = exception; throw; } finally { ctxState?.Dispose(exception: caughtException2); } }