コード例 #1
0
        /// <summary>
        /// Tries to propagate completion from the reader to the writer.
        /// </summary>
        /// <typeparam name="T">The type of the items in the reader and writer.</typeparam>
        /// <param name="reader">The reader.</param>
        /// <param name="writer">The writer.</param>
        /// <param name="passthroughError"><see langword="true"/> - passthrough error, <see langword="false"/> - mute error.</param>
        /// <returns>true, if completion was propagated, false otherwise.</returns>
        public static bool TryPropagateCompletion <T>(
            this IChannelReader <T> reader,
            IChannelWriter <T> writer,
            bool passthroughError = true)
        {
            VxArgs.NotNull(reader, nameof(reader));
            VxArgs.NotNull(writer, nameof(writer));

            if (reader.Completion.IsCompleted)
            {
                Exception error = null;
                try
                {
                    reader.Completion.GetAwaiter().GetResult();
                }
                catch (Exception ex)
                {
                    if (passthroughError)
                    {
                        error = ex;
                    }
                }

                return(writer.TryComplete(error));
            }

            return(false);
        }
コード例 #2
0
        /// <summary>
        /// The parallel loop with async body.
        /// </summary>
        /// <typeparam name="T">The type of the data in the <paramref name="source"/>.</typeparam>
        /// <param name="source">An enumerable data source.</param>
        /// <param name="body">The async delegate that is invoked once per iteration.</param>
        /// <param name="maxDegreeOfParallelism">The  maximum number of concurrent tasks enabled in this operation.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <param name="scheduler">The tasks scheduler.</param>
        /// <returns>Async execution TPL task.</returns>
        public static Task ParallelForEachAsync <T>(
            this IEnumerable <T> source,
            Func <T, Task> body,
            int?maxDegreeOfParallelism          = null,
            CancellationToken cancellationToken = default,
            [CanBeNull] TaskScheduler scheduler = null)
        {
            VxArgs.NotNull(body, nameof(body));

            if (maxDegreeOfParallelism == null)
            {
                maxDegreeOfParallelism = ProcessorsCount;
            }

            int parallelTasksCount = maxDegreeOfParallelism.Value;

            if (source is IReadOnlyCollection <T> rc)
            {
                parallelTasksCount = Math.Min(parallelTasksCount, rc.Count);
            }
            else if (source is ICollection <T> c)
            {
                parallelTasksCount = Math.Min(parallelTasksCount, c.Count);
            }

            return(ParallelForEachAsync(
                       new ConcurrentEnumerator <T, IEnumerator <T> >(source.GetEnumerator()),
                       body,
                       parallelTasksCount,
                       cancellationToken,
                       scheduler));
        }
コード例 #3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="JsonRouterLogger"/> class.
        /// </summary>
        /// <param name="innerLoggers">Inner loggers to route entries to.</param>
        public JsonRouterLogger(params IJsonLogger[] innerLoggers)
        {
            VxArgs.NotNull(innerLoggers, nameof(innerLoggers));

            _innerLoggers    = innerLoggers;
            SerializerSource = _innerLoggers.FirstOrDefault()?.SerializerSource ?? JsonDefaults.RestRpcSerializerSource;
        }
コード例 #4
0
        public IxPerResolveProvider(
            IxHost host,
            [CanBeNull] IxProviderNode parentNode,
            IxProviderNodeConfig config,
            [CanBeNull] IxInstanceFactory instanceFactory,
            IxVisibilityFilter exportFilter,
            IxVisibilityFilter exportToParentFilter,
            IxVisibilityFilter importFilter,
            IxScopeBinderDelegate scopeBinder,
            bool autoDisposeEnabled,
            IxDisposeHandlerDelegate disposeHandler)
            : base(
                host,
                parentNode,
                config,
                instanceFactory,
                exportFilter,
                exportToParentFilter,
                importFilter,
                scopeBinder,
                autoDisposeEnabled,
                disposeHandler)
        {
            VxArgs.NotNull(parentNode, nameof(parentNode));
            VxArgs.NotNull(instanceFactory, nameof(instanceFactory));

            // Adding self provided as default for children.
            VisibleNodes.Add(new IxIdentifier(Identifier.Type), new IxResolvePath(this, new IxProviderNode[] { }));
        }
コード例 #5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="WebHostDeployment"/> class.
        /// </summary>
        /// <param name="webHostBuilder">Web host builder to inject to.</param>
        /// <param name="appConfig">Application configuration root.</param>
        /// <param name="config">Deployment configuration.</param>
        public WebHostDeployment(
            IWebHostBuilder webHostBuilder,
            IConfigurationRoot appConfig,
            WebHostDeploymentConfig config)
        {
            VxArgs.NotNull(webHostBuilder, nameof(webHostBuilder));
            VxArgs.NotNull(appConfig, nameof(appConfig));
            VxArgs.NotNull(config, nameof(config));

            string urls = null;

            if (config.UrlsConfigKey != null)
            {
                urls = appConfig.GetValue <string>(config.UrlsConfigKey);
            }

            if (urls == null && config.DefaultUrls != null)
            {
                urls = config.DefaultUrls;
            }

            if (urls != null)
            {
                webHostBuilder
                .UseUrls(urls);
            }
        }
コード例 #6
0
        /// <inheritdoc/>
        public Task ReadFromFile(Func <string, Task> readProc)
        {
            VxArgs.NotNull(readProc, nameof(readProc));

            // TODO: Temporary file creation is required.
            throw new NotImplementedException();
        }
コード例 #7
0
        /// <summary>
        /// The parallel loop with async body.
        /// TODO: Add yield period option.
        /// </summary>
        /// <typeparam name="T">The type of the data in the <paramref name="source"/>.</typeparam>
        /// <typeparam name="TList">The type of the list.</typeparam>
        /// <param name="source">An enumerable data source.</param>
        /// <param name="body">The async delegate that is invoked once per iteration.</param>
        /// <param name="maxDegreeOfParallelism">The  maximum number of concurrent tasks enabled in this operation.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <param name="scheduler">The tasks scheduler.</param>
        /// <returns>Async execution TPL task.</returns>
        public static Task ParallelForEachAsync <T, TList>(
            this TList source,
            Func <T, Task> body,
            int?maxDegreeOfParallelism          = null,
            CancellationToken cancellationToken = default,
            [CanBeNull] TaskScheduler scheduler = null)
            where TList : IReadOnlyList <T>
        {
            VxArgs.NotNull(body, nameof(body));

            int parallelTasksCount = maxDegreeOfParallelism ?? ProcessorsCount;

            parallelTasksCount = Math.Min(parallelTasksCount, source.Count);

            if (source.Count / 10 > parallelTasksCount)
            {
                return(ParallelForEachFastAsync(
                           source,
                           body,
                           parallelTasksCount,
                           cancellationToken,
                           scheduler));
            }

            return(ParallelForEachAsync(
                       new ListConcurrentEnumerator <T, TList>(source),
                       body,
                       parallelTasksCount,
                       cancellationToken,
                       scheduler));
        }
コード例 #8
0
ファイル: ChannelAdapter.cs プロジェクト: dmitriyse/ClrCoder
        /// <summary>
        /// Initializes a new instance of the <see cref="ChannelAdapter{T}"/> class.
        /// </summary>
        /// <param name="innerChannel">The inner channel.</param>
        public ChannelAdapter(Channel <T> innerChannel)
        {
            VxArgs.NotNull(innerChannel, nameof(innerChannel));

            InnerChannel = innerChannel;
            Reader       = new ChannelAdapterReader(this);
            Writer       = new ChannelAdapterWriter(this);
        }
コード例 #9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ManagedArrayResource{T}"/> class.
        /// </summary>
        /// <param name="array">The array to represent as a resource.</param>
        /// <param name="unmanagedAccessor">The accessor to the unmanaged memory, parameters</param>
        internal ManagedArrayResource(T[] array, Func <UnmanagedMemoryAsyncAction, Task> unmanagedAccessor)
        {
            VxArgs.NotNull(array, nameof(array));
            VxArgs.NotNull(unmanagedAccessor, nameof(array));

            Array = array;
            _unmanagedAccessor = unmanagedAccessor;
        }
コード例 #10
0
        public ClusterObjectKey(ClusterNodeKey hostNode, Int128 id)
        {
            VxArgs.NotNull(hostNode, nameof(hostNode));

            HostNode = hostNode;

            Id = id;
        }
コード例 #11
0
        /// <inheritdoc/>
        public virtual async Task ReadFromStream(Func <Stream, Task> readProc)
        {
            VxArgs.NotNull(readProc, nameof(readProc));

            using (var fileStream = File.OpenRead(_fullFilePath))
            {
                await readProc(fileStream);
            }
        }
コード例 #12
0
        /// <inheritdoc/>
        public async Task WriteToStream(Func <Stream, Task> writeProc)
        {
            VxArgs.NotNull(writeProc, nameof(writeProc));

            using (var fileStream = File.OpenRead(_fullFilePath))
            {
                await writeProc(fileStream);
            }
        }
コード例 #13
0
        public KeyedCollectionEx(IEnumerable <TValue> items) : this()
        {
            VxArgs.NotNull(items, nameof(items));

            foreach (var item in items)
            {
                _inner.Add(item.Key, item);
            }
        }
コード例 #14
0
ファイル: ThreadPoolBase.cs プロジェクト: dmitriyse/ClrCoder
        /// <summary>
        /// Queues new work item to thread pool.
        /// </summary>
        /// <param name="action">The action to execute.</param>
        /// <param name="state"></param>
        public void QueueWorkItem(Action <object> action, [CanBeNull] object state)
        {
            VxArgs.NotNull(action, nameof(action));

#if !NETSTANDARD1_0
            _queuedTasks.Add(new ThreadPoolTask(action, state));
#else
            throw new NotImplementedException();
#endif
        }
コード例 #15
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ChannelWriterMultiplexer{T}"/> class.
 /// </summary>
 /// <param name="innerWriters">The list of inner writers.</param>
 /// <param name="cloneFunc">The item clone func.</param>
 public ChannelWriterMultiplexer(
     IReadOnlyCollection <IChannelWriter <T> > innerWriters,
     Func <T, T> cloneFunc = null)
 {
     VxArgs.NotEmptyReadOnly(innerWriters, nameof(innerWriters));
     _innerWriters  = innerWriters.Select(x => new InnerWriterHandler(this, x)).ToArray();
     _cloneFunc     = cloneFunc ?? (x => x);
     _completionTcs = new TaskCompletionSource <VoidResult>();
     Completion     = new ValueTask(_completionTcs.Task);
 }
コード例 #16
0
        public void ValidAbsoluteUriTest()
        {
            // ReSharper disable once NotResolvedInText
            Action a = () => { VxArgs.ValidAbsoluteUri("http://valid.uri", "test"); };

            a();

            // ReSharper disable once NotResolvedInText
            a = () => { VxArgs.ValidAbsoluteUri("/../valid.uri", "test"); };
            a.ShouldThrow <ArgumentException>().WithInnerException <UriFormatException>();
        }
コード例 #17
0
        /// <summary>
        /// Posts binary data to the url.
        /// </summary>
        /// <param name="url">Flurl url.</param>
        /// <param name="content">Binary content to send.</param>
        /// <param name="setHeadersAction">Action that setups headers.</param>
        /// <param name="cancellationToken">Send cancellation token.</param>
        /// <returns></returns>
        public static Task <HttpResponseMessage> PostBytesAsync(
            this Url url,
            byte[] content,
            Action <HttpContentHeaders> setHeadersAction = null,
            CancellationToken cancellationToken          = default(CancellationToken))
        {
            VxArgs.NotNull(url, nameof(url));
            VxArgs.NotNull(content, nameof(content));

            return(PostBytesAsync(new FlurlRequest(url), content, setHeadersAction, cancellationToken));
        }
コード例 #18
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FileBinaryResource"/> class.
        /// </summary>
        /// <param name="filePath">The file path.</param>
        public FileBinaryResource(UPath filePath)
        {
            VxArgs.NotNull(filePath, nameof(filePath));

            _fullFilePath = filePath.Normalize().ToPlatformPath();

            if (!filePath.FileExists())
            {
                string platformFilePath = filePath.ToPlatformPath();
                throw new FileNotFoundException($"{platformFilePath} does not exists.", platformFilePath);
            }
        }
コード例 #19
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ChannelRawVideoStreamReaderAdapter"/> class.
        /// </summary>
        /// <param name="innerReader">The BCL channel reader.</param>
        /// <param name="videoFormat">The format of the video stream.</param>
        /// <param name="firstFrameInstant">Binding of the video stream to the real world.</param>
        public ChannelRawVideoStreamReaderAdapter(
            IChannelReader <IRawVideoFrame> innerReader,
            RawVideoStreamFormat videoFormat,
            Instant?firstFrameInstant)
        {
            VxArgs.NotNull(innerReader, nameof(innerReader));
            VxArgs.NotNull(videoFormat, nameof(videoFormat));

            InnerReader       = innerReader;
            VideoFormat       = videoFormat;
            FirstFrameInstant = firstFrameInstant;
        }
コード例 #20
0
        /// <summary>
        /// Copies data from stream to stream with limit on maximal written data.
        /// </summary>
        /// <param name="stream">Source stream.</param>
        /// <param name="targetStream">Target stream.</param>
        /// <param name="maxWriteAmount">Maximal allwed amount to write.</param>
        /// <returns>Async execution TPL task.</returns>
        /// <exception cref="IOException">Maximal allowed write reached.</exception>
        public static async Task CopyToWithLimitAsync(this Stream stream, Stream targetStream, long maxWriteAmount)
        {
            VxArgs.NotNull(stream, nameof(stream));
            VxArgs.NotNull(targetStream, nameof(targetStream));
            if (maxWriteAmount < 0)
            {
                throw new ArgumentOutOfRangeException(
                          nameof(maxWriteAmount),
                          "Maximal write amount should be positive.");
            }

            await stream.CopyToAsync(new LimitWriteStream(targetStream, maxWriteAmount));
        }
コード例 #21
0
        /// <summary>
        /// Posts binary data to the flurl client.
        /// </summary>
        /// <param name="client">Flurl fluent syntax.</param>
        /// <param name="content">Binary content to send.</param>
        /// <param name="setHeadersAction">Action that setups headers.</param>
        /// <param name="cancellationToken">Send cancellation token.</param>
        /// <returns></returns>
        public static Task <HttpResponseMessage> PostBytesAsync(
            this IFlurlRequest client,
            byte[] content,
            Action <HttpContentHeaders> setHeadersAction = null,
            CancellationToken cancellationToken          = default(CancellationToken))
        {
            VxArgs.NotNull(client, nameof(client));
            VxArgs.NotNull(content, nameof(content));

            var httpContent = new ByteArrayContent(content);

            setHeadersAction?.Invoke(httpContent.Headers);

            return(client.PostAsync(httpContent, cancellationToken));
        }
コード例 #22
0
        /// <summary>
        /// Gets value from the async results dictionary or call create methods.
        /// </summary>
        /// <typeparam name="TKey">The type of the resource key.</typeparam>
        /// <typeparam name="TValue">The type of the result value.</typeparam>
        /// <param name="asyncResultsDictionary">The dictionary with asynchronous results.</param>
        /// <param name="key">The key of result to get or create.</param>
        /// <param name="createFunc">The result creation async function.</param>
        /// <param name="allowRetry">Allows to retry call to createFunc when it throws an exception.</param>
        /// <returns>Async result task, corresponding to the specified key.</returns>
        public static ValueTask <TValue> GetOrCreateAsync <TKey, TValue>(
            this IDictionary <TKey, ValueTask <TValue> > asyncResultsDictionary,
            TKey key,
            Func <TKey, ValueTask <TValue> > createFunc,
            bool allowRetry = true)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            VxArgs.NotNull(asyncResultsDictionary, nameof(asyncResultsDictionary));
            VxArgs.NotNull(createFunc, nameof(createFunc));

            lock (asyncResultsDictionary)
            {
                if (asyncResultsDictionary.TryGetValue(key, out var asyncResult))
                {
                    return(asyncResult);
                }

                asyncResult = new ValueTask <TValue>(
                    Task.Run(
                        async() =>
                {
                    try
                    {
                        return(await createFunc(key));
                    }
                    catch (Exception)
                    {
                        if (allowRetry)
                        {
                            lock (asyncResultsDictionary)
                            {
                                asyncResultsDictionary.Remove(key);
                            }
                        }

                        throw;
                    }
                }));

                asyncResultsDictionary.Add(key, asyncResult);
                return(asyncResult);
            }
        }
コード例 #23
0
        /// <summary>
        /// Creates or updates entity.
        /// </summary>
        /// <remarks>
        /// Update or Create operations are performed in the critical section, so left any processing out-of those functions.
        /// </remarks>
        /// <param name="entityKey">The entity key.</param>
        /// <param name="updateAction">The update action. It will be called when entity with the specified key exists.</param>
        /// <param name="createFunc">The create function. It will be called when entity with the specified key not exists.</param>
        public void CreateOrUpdateEntity(TKey entityKey, Action <TEntity> updateAction, Func <TEntity> createFunc)
        {
            VxArgs.NotNull(entityKey, nameof(entityKey));
            VxArgs.NotNull(updateAction, nameof(updateAction));
            VxArgs.NotNull(createFunc, nameof(createFunc));

            lock (_entities)
            {
                if (_entities.TryGetValue(entityKey, out var entity))
                {
                    updateAction(entity);
                }
                else
                {
                    TEntity newEntity = createFunc();

                    // Following max capacity rule.
                    if (MaxCapacity != null && _gcFifoQueue != null)
                    {
                        if (_gcFifoQueue.Count >= MaxCapacity)
                        {
                            if (_gcFifoQueue.TryDequeue(out var itemToRemove))
                            {
                                _entities.Remove(itemToRemove.Key);
                            }
                        }

                        _gcFifoQueue.AddFirst(entityKey, default);
                    }

                    _entities.Add(entityKey, newEntity);
                    Critical.Assert(
                        newEntity.Key.Equals(entityKey),
                        "Created entity should have the same key as was queried to the CreateOrUpdateEntity method.");
                }
            }
        }
コード例 #24
0
 /// <summary>
 /// Initializes a new instance of the
 /// <see cref="LwtInMemoryStorageRepository{TPersistence,TUnitOfWork,TStorage,TRepository,TKey,TEntity}"/>
 /// class.
 /// </summary>
 /// <param name="storage">Storage that is serviced by <c>this</c> repository.</param>
 public LwtInMemoryStorageRepository(TStorage storage)
 {
     VxArgs.NotNull(storage, nameof(storage));
     Storage = storage;
 }
コード例 #25
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ClassJsonLogger{T}"/> class.
 /// </summary>
 /// <param name="innerLogger">Next logger in chain.</param>
 public ClassJsonLogger(IJsonLogger innerLogger)
 {
     VxArgs.NotNull(innerLogger, nameof(innerLogger));
     _innerLogger     = innerLogger;
     SerializerSource = innerLogger.SerializerSource;
 }
コード例 #26
0
 public static IxDelegateInstanceBuilderConfig New <T1, T2, T3, T4, T5, TResult>(
     Func <T1, T2, T3, T4, T5, ValueTask <TResult> > func)
 {
     VxArgs.NotNull(func, nameof(func));
     return(new IxDelegateInstanceBuilderConfig(func));
 }
コード例 #27
0
        /// <inheritdoc/>
        public async Task WriteToStream(Func <Stream, Task> writeProc)
        {
            VxArgs.NotNull(writeProc, nameof(writeProc));

            await ReadOrWriteStreamInternal(writeProc);
        }
コード例 #28
0
        /// <inheritdoc/>
        public async Task ReadFromStream(Func <Stream, Task> readProc)
        {
            VxArgs.NotNull(readProc, nameof(readProc));

            await ReadOrWriteStreamInternal(readProc);
        }
コード例 #29
0
 /// <inheritdoc/>
 public async Task ReadFromMemory(Func <IntPtr, long, Task> readProc)
 {
     VxArgs.NotNull(readProc, nameof(readProc));
     await readProc(_bufferPtr, _length);
 }
コード例 #30
0
ファイル: ClusterNodeKey.cs プロジェクト: dmitriyse/ClrCoder
 public ClusterNodeKey(string code)
 {
     VxArgs.NonNullOrWhiteSpace(code, nameof(code));
     Code = code;
 }