Exemplo n.º 1
0
Arquivo: Taxi.cs Projeto: vonwenm/Jibu
 // 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();
 }
Exemplo n.º 2
0
        /// <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.");
        }
Exemplo n.º 3
0
        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
            //}
        }
Exemplo n.º 5
0
    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);
        }
Exemplo n.º 7
0
        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();
        }
Exemplo n.º 8
0
 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);
         });
     }
 }
Exemplo n.º 9
0
        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);
        }
Exemplo n.º 10
0
            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;
            }
Exemplo n.º 11
0
        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);
            }
        }
Exemplo n.º 12
0
        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();
        }
Exemplo n.º 13
0
        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;
        }
Exemplo n.º 14
0
        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();
        }
Exemplo n.º 15
0
        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);
            }
        }
Exemplo n.º 16
0
        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();
        }
Exemplo n.º 17
0
        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();
                    }
                }
            }
        }
Exemplo n.º 18
0
        //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);
            }
        }
Exemplo n.º 19
0
        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();
                    }
                }
            });
        }
Exemplo n.º 20
0
        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);
                    }
                }
            }
        }
Exemplo n.º 21
0
    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"),
                };
            }
Exemplo n.º 22
0
        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);
        }
Exemplo n.º 23
0
        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();
        }
Exemplo n.º 24
0
        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();
        }
Exemplo n.º 26
0
    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;
 }
Exemplo n.º 28
0
 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;
 }
Exemplo n.º 29
0
        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;
        }
Exemplo n.º 30
0
        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);
        }
Exemplo n.º 31
0
        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");
            }
        }
Exemplo n.º 32
0
 public Customer(String name, ChannelWriter<Customer> customers)
 {
     this.name = name;
     this.customers = customers;
 }
Exemplo n.º 33
0
 public Customers(ChannelWriter<Tuple<int, int, string>> info)
 {
     infoChannel = info;
     rand = new Random();
     timer = new Timer();
 }