// The constructor taking the input info channel and the output acknowledge channel. public Taxi(ChannelReader<Tuple<int, int, string>> info, ChannelWriter<string> ack) { customerInfoChannel = info; ackChannel = ack; timer = new Timer(); rand = new Random(); }
/// <summary> /// Adds a message to be displayed. /// </summary> /// <param name="message"><see cref="LoggerJsonMessage"/>.</param> /// <param name="token">Optional <see cref="CancellationToken"/>.</param> public void AddMessage(LoggerJsonMessage message, CancellationToken token = default) { ChannelWriter <LoggerJsonMessage> Writer = Messages.Writer; while (true) { ValueTask <bool> Task = Writer.WaitToWriteAsync(token); if (!(Task.IsCompleted ? Task.Result : Task.AsTask().GetAwaiter().GetResult())) { break; } if (Writer.TryWrite(message)) { return; } } throw new InvalidOperationException("MessageManager has closed."); }
public async void ExampleChannelProducerConsumerAsync() { Channel <int> queue = Channel.CreateUnbounded <int>(); ChannelWriter <int> writer = queue.Writer; await writer.WriteAsync(1); await writer.WriteAsync(2); await writer.WriteAsync(3); writer.Complete(); ChannelReader <int> reader = queue.Reader; await foreach (var x in reader.ReadAllAsync()) { Console.WriteLine($"Channel: {x}"); } }
async ValueTask ProducerAsync(ChannelWriter <Uri> uriChannel, IEnumerable <Uri> uris) //!SPOT: Replaced task to valueTask { //Mixing Async + Sync //In case of a single producer it is not a problem, but can't scale well foreach (var uri in uris) { await uriChannel.WaitToWriteAsync(); //Waits until there is a free space if (!uriChannel.TryWrite(uri)) //!SPOT: posting data is synchronous { return; //It returns false if the channel is closed between WaitToWriteAsync and TryWrite } } //Pure async //foreach (var uri in uris) //{ // await uriChannel.WriteAsync(uri); //Waits until there is a free place & posts the data //} }
public async Task Sender(ChannelWriter <string> writer) { MySongs mySongs = new MySongs(); await Task.Run(() => Parallel.ForEach(mySongs.songs, song => { if (song.Tags != null) { Parallel.ForEach(song.Tags, tag => { writer.WriteAsync(tag); }); } ; }) ); Task.WaitAll(); writer.Complete(); return; }
private protected DictionaryCacheBase(IEqualityComparer <TKey> keyComparer, TimeSpan keyExpiryProcessorInterval) { _values = new ConcurrentDictionary <TKey, ValueAndExpiry>(keyComparer ?? EqualityComparer <TKey> .Default); _keysToExpireHeap = new MinHeap <KeyAndExpiry>(KeyAndExpiryComparer.Instance); _valueAndExpiryPool = new HighCapacityObjectPool <ValueAndExpiry>(() => new ValueAndExpiry(), 1000); var keysToBePutIntoExpiryHeapChannel = Channel.CreateUnbounded <KeyAndExpiry>(new UnboundedChannelOptions { SingleReader = true }); _keysToBePutIntoExpiryHeapReader = keysToBePutIntoExpiryHeapChannel.Reader; _keysToBePutIntoExpiryHeapWriter = keysToBePutIntoExpiryHeapChannel.Writer; _keyExpiryProcessorInterval = keyExpiryProcessorInterval; _keyExpiryProcessorTimer = new Timer( _ => ProcessKeyExpiryDates(), null, (int)keyExpiryProcessorInterval.TotalMilliseconds, -1); }
async Task FetchEvents(long from, ChannelWriter <PartitionUpdateEvent> replayChannelWriter, ChannelWriter <TrackedObjectKey> prefetchChannelWriter) { await foreach (var partitionEvent in this.EventsToReplay(from)) { this.cancellationToken.ThrowIfCancellationRequested(); await replayChannelWriter.WriteAsync(partitionEvent); if (partitionEvent is IRequiresPrefetch evt) { foreach (var key in evt.KeysToPrefetch) { await prefetchChannelWriter.WriteAsync(key); } } } replayChannelWriter.Complete(); prefetchChannelWriter.Complete(); }
public void RegisterConnection(string connectionId, Y[] ids, ChannelWriter <T> writer) { if (ids != null && ids.Any()) { var subscription = new ChannelWriterSubscription <T, Y>(writer, ids); _subscriptions.AddOrUpdate(connectionId, subscription, (cl, sub) => { sub.ChannelWriter?.Complete(); return(subscription); }); } else { _channels.AddOrUpdate(connectionId, writer, (cl, cw) => { cw?.Complete(); return(writer); }); } }
protected Connection( ConnectionContext connection, ConnectionDelegate middleware, ConnectionCommon shared) { #if !NETCOREAPP this.handleMessageCallback = obj => this.OnReceivedMessage((Message)obj); #endif this.Context = connection ?? throw new ArgumentNullException(nameof(connection)); this.middleware = middleware ?? throw new ArgumentNullException(nameof(middleware)); this.shared = shared; this.outgoingMessages = Channel.CreateUnbounded <Message>(OutgoingMessageChannelOptions); this.outgoingMessageWriter = this.outgoingMessages.Writer; // Set the connection on the connection context so that it can be retrieved by the middleware. this.Context.Features.Set <Connection>(this); this.RemoteEndPoint = NormalizeEndpoint(this.Context.RemoteEndPoint); this.LocalEndPoint = NormalizeEndpoint(this.Context.LocalEndPoint); }
private protected IntegrationInstance() { var toInstance = Channel.CreateUnbounded <object>(new UnboundedChannelOptions { SingleReader = true, SingleWriter = true }); _toInstanceReader = toInstance.Reader; _toInstanceWriter = toInstance.Writer; var fromInstance = Channel.CreateUnbounded <object>(new UnboundedChannelOptions { SingleReader = true, SingleWriter = true }); _fromInstanceReader = fromInstance.Reader; _fromInstanceWriter = fromInstance.Writer; }
private async Task WriteNumberAsync(ChannelWriter <int> channelWriter, int numberCount, CancellationToken cancellationToken) { Exception localException = null; try { for (var i = 0; i < numberCount; i++) { await channelWriter.WriteAsync(i, cancellationToken); } } catch (Exception ex) { localException = ex; } finally { channelWriter.Complete(localException); } }
private async Task WriteDateAsync(ChannelWriter <string> writer, CancellationToken token) { try { while (true) { token.ThrowIfCancellationRequested(); await writer.WriteAsync(DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.fffffff")); await Task.Delay(10, token); } } catch { writer.TryComplete(); } writer.TryComplete(); }
protected Connection( ConnectionContext connection, ConnectionDelegate middleware, IServiceProvider serviceProvider, INetworkingTrace trace) { this.Context = connection ?? throw new ArgumentNullException(nameof(connection)); this.middleware = middleware ?? throw new ArgumentNullException(nameof(middleware)); this.serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider)); this.Log = trace ?? throw new ArgumentNullException(nameof(trace)); this.outgoingMessages = Channel.CreateUnbounded <Message>(OutgoingMessageChannelOptions); this.outgoingMessageWriter = this.outgoingMessages.Writer; // Set the connection on the connection context so that it can be retrieved by the middleware. this.Context.Features.Set <Connection>(this); this.RemoteEndPoint = NormalizeEndpoint(this.Context.RemoteEndPoint); this.LocalEndPoint = NormalizeEndpoint(this.Context.LocalEndPoint); this.IsValid = true; }
private async static void ScanRunner(ChannelReader <string> inputReader, ChannelWriter <string> outputWriter) { var scanner = new NmapScanner(); while (await inputReader.WaitToReadAsync()) { string target; string output; while (inputReader.TryRead(out target)) { Console.WriteLine($"Scanning {target}"); output = scanner.RunNmapScan(target); outputWriter.TryWrite($"Results for {target}\n{output}"); } } //outputWriter.TryComplete(); }
public async void HandleAsync( ChannelReader <byte> reader, ChannelWriter <byte> writer, CancellationToken cancellationToken) { try { while (!cancellationToken.IsCancellationRequested) { byte opcode = await reader.ReadAsync(cancellationToken); Handlers.IPacketHandler packetHandler = router.GetPacketHandler(opcode); await packetHandler.HandleAsync(reader, writer, clientModel); } } catch (Exception ex) { logger.Error("Packet handler error", ex); } }
private async Task WriteItemsAsync( ChannelWriter <int> writer, int count, int delay, CancellationToken cancellationToken) { for (var i = 0; i < count; i++) { // Check the cancellation token regularly so that the server will stop // producing items if the client disconnects. cancellationToken.ThrowIfCancellationRequested(); await writer.WriteAsync(i); // Use the cancellationToken in other APIs that accept cancellation // tokens so the cancellation can flow down to them. await Task.Delay(delay, cancellationToken); } writer.TryComplete(); }
public async Task WriteAsyncThenReadAsync() { Channel <int> channel = CreateChannel(); ChannelReader <int> reader = channel.Reader; ChannelWriter <int> writer = channel.Writer; foreach (BenchmarkIteration iteration in Benchmark.Iterations) { long iters = Benchmark.InnerIterationCount; using (iteration.StartMeasurement()) { for (int i = 0; i < iters; i++) { await writer.WriteAsync(i); await reader.ReadAsync(); } } } }
//Handle on Multiple Threads public TPLChannelsClass(int threads) { var channel = Channel.CreateUnbounded <string>(); var reader = channel.Reader; _writer = channel.Writer; for (int i = 0; i < threads; i++) { var threadId = i; Task.Factory.StartNew(async() => { // Wait while channel is not empty and still not completed while (await reader.WaitToReadAsync()) { var job = await reader.ReadAsync(); Console.WriteLine(job); } }, TaskCreationOptions.LongRunning); } }
public ChannelQueue() { Channel <Action> channel = Channel.CreateUnbounded <Action>(new UnboundedChannelOptions { SingleReader = true }); ChannelReader <Action> reader = channel.Reader; _channelWriter = channel.Writer; Task.Run(async() => { while (await reader.WaitToReadAsync()) { while (reader.TryRead(out Action job)) { job.Invoke(); } } }); }
private async Task ProduceIndexActionsAsync( ChannelWriter <IndexAction <KeyedDocument> > channel, ConcurrentBag <string> packageIds, CancellationToken cancellationToken) { await ParallelAsync.RunAsync( packageIds, ProduceIndexActionsAsync, cancellationToken); _logger.LogInformation("Finished producing index actions"); channel.Complete(); return; async Task ProduceIndexActionsAsync(string packageId, CancellationToken cancellationToken1) { _logger.LogInformation("Adding package {PackageId}...", packageId); var packages = await _packages.FindAsync(packageId, includeUnlisted : false); if (packages.Count == 0) { _logger.LogWarning( "Could not find any listed packages for package ID {PackageId}, skipping...", packageId); return; } var registration = new PackageRegistration( packageId, packages); foreach (var action in _actionBuilder.AddPackage(registration)) { if (!channel.TryWrite(action)) { await channel.WriteAsync(action, cancellationToken); } } } }
private async Task FindSystem(ChannelReader <long> reports, ChannelWriter <long> movements) { long steps = 0; var area = new Dictionary <Point, PointState>(); var location = new Point(0, 0); area[location] = PointState.Clear; var previouslyWall = false; var nextMove = Direction.East; await movements.WriteAsync((long)nextMove); while (await reports.WaitToReadAsync()) { var report = (PointState)await reports.ReadAsync(); steps++; var expectedLocation = Move(location, nextMove); area[expectedLocation] = report; if (report == PointState.Wall) { (nextMove, previouslyWall) = (nextMove, previouslyWall) switch { // Turn right by default (Direction.North, false) => (Direction.East, true), (Direction.East, false) => (Direction.South, true), (Direction.South, false) => (Direction.West, true), (Direction.West, false) => (Direction.North, true), // If we hit a wall after turning right, turn back around to go left (Direction.North, true) => (Direction.West, true), (Direction.East, true) => (Direction.North, true), (Direction.South, true) => (Direction.East, true), (Direction.West, true) => (Direction.South, true), // (Direction.North, true) => (Direction.South, false), // (Direction.East, true) => (Direction.West, false), // (Direction.South, true) => (Direction.North, false), // (Direction.West, true) => (Direction.East, false), _ => throw new NotSupportedException("Unexpected value"), }; }
public ChannelsQueue() { //var channel = Channel.CreateUnbounded<string>(); var channel = Channel.CreateUnbounded <Action>(new UnboundedChannelOptions() { SingleReader = true }); var reader = channel.Reader; _writer = channel.Writer; Task.Factory.StartNew(async() => { // Wait while channel is not empty and still not completed while (await reader.WaitToReadAsync()) { var job = await reader.ReadAsync(); Console.WriteLine(job); } }, TaskCreationOptions.LongRunning); }
private async Task WriteItemsAsync( ChannelWriter <int> writer, int count, int delay) { try { for (var i = 0; i < count; i++) { await writer.WriteAsync(i); await Task.Delay(delay); } } catch (Exception ex) { writer.TryComplete(ex); } writer.TryComplete(); }
public ObjectPool(ObjectPoolSettings settings, Func <T> objectFactory) { if (settings.MaxPoolSize < settings.MinPoolSize) { throw new ArgumentException( $"Object can't have MaxPoolSize {settings.MaxPoolSize} under MinPoolSize {settings.MinPoolSize}"); } _settings = settings; _objectFactory = objectFactory; var idleChannel = Channel.CreateUnbounded <T>(); _idleObjectReader = idleChannel.Reader; _idleObjectWriter = idleChannel.Writer; _maxPoolSize = settings.MaxPoolSize; _minPoolSize = settings.MinPoolSize; _pooledObjects = new T[_maxPoolSize]; }
/// <summary> /// Waits for opportunity to write to a channel and throws a ChannelClosedException if the channel is closed. /// </summary> /// <typeparam name="T">The type being written to the channel</typeparam> /// <param name="writer">The channel writer.</param> /// <param name="cancellationToken">An optional cancellation token.</param> public static ValueTask WaitToWriteAndThrowIfClosedAsync <T>(this ChannelWriter <T> writer, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { return(new ValueTask(Task.FromCanceled(cancellationToken))); } var waitForWrite = writer.WaitToWriteAsync(cancellationToken); if (!waitForWrite.IsCompletedSuccessfully) { return(ThrowChannelClosedExceptionIfFalse(waitForWrite)); } if (waitForWrite.Result) { return(new ValueTask()); } throw new ChannelClosedException(); }
async Task Test() { Channel <int> queue = Channel.CreateUnbounded <int>(); // Producer code ChannelWriter <int> writer = queue.Writer; await writer.WriteAsync(7); await writer.WriteAsync(13); writer.Complete(); // Consumer code // Displays "7" followed by "13". ChannelReader <int> reader = queue.Reader; await foreach (int value in reader.ReadAllAsync()) { Trace.WriteLine(value); } }
public SynchronizeEmbyLibraryByIdHandler( IMediaSourceRepository mediaSourceRepository, IEmbySecretStore embySecretStore, IEmbyMovieLibraryScanner embyMovieLibraryScanner, IEmbyTelevisionLibraryScanner embyTelevisionLibraryScanner, ILibraryRepository libraryRepository, IEntityLocker entityLocker, IConfigElementRepository configElementRepository, ChannelWriter <IEmbyBackgroundServiceRequest> embyWorkerChannel, ILogger <SynchronizeEmbyLibraryByIdHandler> logger) { _mediaSourceRepository = mediaSourceRepository; _embySecretStore = embySecretStore; _embyMovieLibraryScanner = embyMovieLibraryScanner; _embyTelevisionLibraryScanner = embyTelevisionLibraryScanner; _libraryRepository = libraryRepository; _entityLocker = entityLocker; _configElementRepository = configElementRepository; _embyWorkerChannel = embyWorkerChannel; _logger = logger; }
public SynchronizeJellyfinLibraryByIdHandler( IMediaSourceRepository mediaSourceRepository, IJellyfinSecretStore jellyfinSecretStore, IJellyfinMovieLibraryScanner jellyfinMovieLibraryScanner, IJellyfinTelevisionLibraryScanner jellyfinTelevisionLibraryScanner, ILibraryRepository libraryRepository, IEntityLocker entityLocker, IConfigElementRepository configElementRepository, ChannelWriter <IJellyfinBackgroundServiceRequest> jellyfinWorkerChannel, ILogger <SynchronizeJellyfinLibraryByIdHandler> logger) { _mediaSourceRepository = mediaSourceRepository; _jellyfinSecretStore = jellyfinSecretStore; _jellyfinMovieLibraryScanner = jellyfinMovieLibraryScanner; _jellyfinTelevisionLibraryScanner = jellyfinTelevisionLibraryScanner; _libraryRepository = libraryRepository; _entityLocker = entityLocker; _configElementRepository = configElementRepository; _jellyfinWorkerChannel = jellyfinWorkerChannel; _logger = logger; }
protected virtual void Dispose(bool disposing) { if (_disposed) { return; } if (_channel is null && _source.Task.IsCompletedSuccessfully) { _channel = _source.Task.Result; _writer = _channel.Writer; } if (_channel?.Release() ?? false) { _writer?.TryComplete(); } _channel = null; _writer = null; _disposed = true; }
public ChannelReader <string> RunCommand(string cmd) { var channel = Channel.CreateUnbounded <string>(); writer = channel.Writer; var process = new Process() { StartInfo = new ProcessStartInfo { RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true } }; var isLinux = System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(OSPlatform.Linux); if (isLinux) { process.StartInfo.FileName = "/bin/bash"; process.StartInfo.Arguments = $"-c \"{cmd.Replace("\"", "\\\"")}\""; } else { process.StartInfo.FileName = "cmd.exe"; process.StartInfo.Arguments = $"/c {cmd}"; } process.OutputDataReceived += ReadOutputHandler; process.Exited += Process_Exited; process.Start(); process.BeginOutputReadLine(); return(channel.Reader); }
private async Task ParseLines(ChannelReader <LogDatum> reader, ChannelWriter <ILine> writer) { int count = 0; try { // https://gist.github.com/AlgorithmsAreCool/b0960ce8a3400305e43fe8ffdf89b32c // because async methods use a state machine to handle awaits // it is safe to await in an infinte loop. Thank you C# compiler gods! // while (await reader.WaitToReadAsync() && !CancelSource.IsCancellationRequested) // { // while (reader.TryRead(out var logLine) && !CancelSource.IsCancellationRequested) // while (await reader.WaitToReadAsync(CancelSource.Token)) // { // while (!CancelSource.IsCancellationRequested && reader.TryRead(out var logLine)) // { // ParseLine(logLine, writer); // } // WriteMessage($"Lines parsed: {count:N0}, {_sw.Elapsed} elapsed"); // } while (true) { var logLine = await reader.ReadAsync(CancelSource.Token); ParseLine(logLine, writer); } } catch (Exception ex) { WriteMessage($"Parse ERROR: {ex.Message}, {ex.GetType()}"); } finally { writer.Complete(); WriteMessage($"Total Lines parsed: {count:N0}, {_sw.Elapsed} elapsed"); } }
public Customer(String name, ChannelWriter<Customer> customers) { this.name = name; this.customers = customers; }
public Customers(ChannelWriter<Tuple<int, int, string>> info) { infoChannel = info; rand = new Random(); timer = new Timer(); }