当前位置: 首页>>代码示例>>C#>>正文


C# BufferBlock类代码示例

本文整理汇总了C#中BufferBlock的典型用法代码示例。如果您正苦于以下问题:C# BufferBlock类的具体用法?C# BufferBlock怎么用?C# BufferBlock使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


BufferBlock类属于命名空间,在下文中一共展示了BufferBlock类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Generate

        public static void Generate(string root)
        {
            Directory.CreateDirectory("docs");

            var _executingDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            File.Copy(Path.Combine(_executingDirectory, "Resources", "Nocco.css"), Path.Combine("docs", "nocco.css"), true);
            File.Copy(Path.Combine(_executingDirectory, "Resources", "prettify.js"), Path.Combine("docs", "prettify.js"), true);

            var getFiles = DirectoryTraveler.Create();
            var readFiles = FileReader.Create();
            var redFileBuffer = new BufferBlock<FileContents>();
            var parseFiles = FileParser.Create();
            var renderCode = CodeRenderer.Create();
            var renderDocs = DocRenderer.Create();
            var generateHtml = HtmlGenerator.Create();
            var persistanceBuffer = new BufferBlock<RenderedFile>();
            var persistFile = FilePersister.Create();

            var propCompl = new DataflowLinkOptions { PropagateCompletion = true };

            getFiles.LinkTo(readFiles, propCompl);
            readFiles.LinkTo(redFileBuffer, propCompl);
            redFileBuffer.LinkTo(parseFiles, propCompl);
            parseFiles.LinkTo(renderCode, propCompl);
            renderCode.LinkTo(renderDocs, propCompl);
            renderDocs.LinkTo(generateHtml, propCompl);
            generateHtml.LinkTo(persistanceBuffer, propCompl);
            persistanceBuffer.LinkTo(persistFile, propCompl);

            getFiles.Post(root);
            getFiles.Complete();

            persistanceBuffer.Completion.Wait();
        }
开发者ID:valdisz,项目名称:nocco,代码行数:34,代码来源:Flow.cs

示例2: Process

    public async Task Process(GamePointer gp, List<PlayerState> players, BufferBlock<UpdatePacket> sendChannel)
    {

      players.Add(_player);

      var squares = gp.Game.GetSquares().Select(x => new SquareDTO(x)).ToArray();

      //FIXME: right now the order is important here, lest we lack player color information when rendering flags
      var json2 = JSON.Serialize<PlayerState[]>(players.ToArray());
      var packet2 = new UpdatePacket()
      {
        Type = "player",
        Data = json2
      };
      var j2 = JSON.Serialize<UpdatePacket>(packet2);
      await _uc.SendAsync(j2);


      var json = JSON.Serialize<SquareDTO[]>(squares);
      var packet = new UpdatePacket()
      {
        Type = "square",
        Data = json
      };

      var j = JSON.Serialize<UpdatePacket>(packet);
      await _uc.SendAsync(j);



    }
开发者ID:slofurno,项目名称:minesweepers,代码行数:31,代码来源:Tasks.cs

示例3: SQLMessageQueue

        public SQLMessageQueue(IDbConnectionProvider connectionProvider, ISQLDialect dialect, QueueName queueName,
            IQueueListener listener, QueueOptions options = default(QueueOptions))
        {
            if (connectionProvider == null) throw new ArgumentNullException("connectionProvider");
            if (dialect == null) throw new ArgumentNullException("dialect");
            if (queueName == null) throw new ArgumentNullException("queueName");
            if (listener == null) throw new ArgumentNullException("listener");

            _connectionProvider = connectionProvider;
            _dialect = dialect;
            _queueName = queueName;

            _listener = listener;
            _autoAcknowledge = options.AutoAcknowledge;
            _maxAttempts = options.MaxAttempts <= 0 ? 10 : options.MaxAttempts;
            _retryDelay = options.RetryDelay < TimeSpan.Zero ? TimeSpan.Zero : options.RetryDelay;

            var concurrencyLimit = options.ConcurrencyLimit <= 0
                ? QueueOptions.DefaultConcurrencyLimit
                : options.ConcurrencyLimit;
            _concurrentMessageProcessingSlot = new SemaphoreSlim(concurrencyLimit);

            _cancellationTokenSource = new CancellationTokenSource();
            _queuedMessages = new BufferBlock<SQLQueuedMessage>(new DataflowBlockOptions
            {
                CancellationToken = _cancellationTokenSource.Token
            });
        }
开发者ID:tdbrian,项目名称:Platibus,代码行数:28,代码来源:SQLMessageQueue.cs

示例4: FilesystemMessageQueue

        public FilesystemMessageQueue(DirectoryInfo directory, IQueueListener listener,
            QueueOptions options = default(QueueOptions))
        {
            if (directory == null) throw new ArgumentNullException("directory");
            if (listener == null) throw new ArgumentNullException("listener");

            _directory = directory;
            _deadLetterDirectory = new DirectoryInfo(Path.Combine(directory.FullName, "dead"));

            _listener = listener;
            _autoAcknowledge = options.AutoAcknowledge;
            _maxAttempts = options.MaxAttempts <= 0 ? 10 : options.MaxAttempts;
            _retryDelay = options.RetryDelay < TimeSpan.Zero ? TimeSpan.Zero : options.RetryDelay;

            var concurrencyLimit = options.ConcurrencyLimit <= 0
                ? QueueOptions.DefaultConcurrencyLimit
                : options.ConcurrencyLimit;
            _concurrentMessageProcessingSlot = new SemaphoreSlim(concurrencyLimit);

            _cancellationTokenSource = new CancellationTokenSource();
            _queuedMessages = new BufferBlock<MessageFile>(new DataflowBlockOptions
            {
                CancellationToken = _cancellationTokenSource.Token
            });
        }
开发者ID:tdbrian,项目名称:Platibus,代码行数:25,代码来源:FilesystemMessageQueue.cs

示例5: TestCaptureOrder

        public void TestCaptureOrder()
        {
            // post source ints
            var intSource = new BufferBlock<int>();
            intSource.Post(1);
            intSource.Post(2);
            intSource.Post(99);
            intSource.Post(98);
            intSource.Complete();

            // capture source order
            var orderedInts = OrderingBlock.CaptureOrder<int, long, long>(
                intSource, intValue => (long)intValue);

            // post longs to combine, in reverse of original order
            var longSource = new BufferBlock<long>();
            longSource.Post(99);
            longSource.Post(98);
            longSource.Post(2);
            longSource.Post(1);
            longSource.Complete();

            // apply source order
            var orderedLongs = orderedInts.ApplyOrder(longSource, longValue => longValue);

            // verify the original order was preserved
            CollectionAssert.AreEqual(new long[] { 1, 2, 99, 98 }, orderedLongs.ToEnumerable().ToList());
        }
开发者ID:cole2295,项目名称:BitSharp,代码行数:28,代码来源:OrderingBlockTest.cs

示例6: TestUtxoLookAheadWithTransactions

        public void TestUtxoLookAheadWithTransactions()
        {
            var deferredCursor = new Mock<IDeferredChainStateCursor>();
            deferredCursor.Setup(x => x.CursorCount).Returns(4);

            var blockTxes = new BufferBlock<DecodedBlockTx>();

            var lookAhead = UtxoLookAhead.LookAhead(blockTxes, deferredCursor.Object);

            var blockTx0 = BlockTx.Create(0, RandomData.RandomTransaction(new RandomDataOptions { TxInputCount = 2 }));
            var blockTx1 = BlockTx.Create(1, RandomData.RandomTransaction(new RandomDataOptions { TxInputCount = 2 }));
            var blockTx2 = BlockTx.Create(2, RandomData.RandomTransaction(new RandomDataOptions { TxInputCount = 2 }));

            blockTxes.Post(blockTx0);
            blockTxes.Post(blockTx1);
            blockTxes.Post(blockTx2);
            blockTxes.Complete();

            // verify each transaction was forwarded
            var expectedBlockTxes = new[] { blockTx0, blockTx1, blockTx2 };
            var warmedTxes = lookAhead.ReceiveAllAsync().Result;
            Assert.AreEqual(3, warmedTxes.Count);
            CollectionAssert.AreEqual(expectedBlockTxes.Select(x => x.Hash).ToList(), warmedTxes.Select(x => x.Hash).ToList());

            // verify each non-coinbase input transaction was warmed up
            var expectedLookups = expectedBlockTxes.Skip(1).SelectMany(x => x.Transaction.Inputs.Select(input => input.PrevTxOutputKey.TxHash));
            foreach (var txHash in expectedLookups)
                deferredCursor.Verify(x => x.WarmUnspentTx(txHash));

            Assert.IsTrue(lookAhead.Completion.Wait(2000));
        }
开发者ID:cole2295,项目名称:BitSharp,代码行数:31,代码来源:UtxoLookAheadTest.cs

示例7: Run

        public void Run()
        {
            Console.WriteLine("Generating first {0} powers of 2.", MaxItems);
            var bufferBlock = new BufferBlock<int>();
            var transformBlock = new TransformBlock<int, double>(i =>
            {
                Thread.Sleep(500);
                return Math.Pow(2, i);
            }, new ExecutionDataflowBlockOptions { BoundedCapacity = 10 });

            var actionBlock = new ActionBlock<double>(async i =>
            {
                await Task.Delay(1000);
                Console.WriteLine(i);
                _waitHandle.Signal();
            }, new ExecutionDataflowBlockOptions { BoundedCapacity = 10 });

            bufferBlock.LinkTo(transformBlock);
            transformBlock.LinkTo(actionBlock);

            Enumerable.Range(1, MaxItems)
                .ToList()
                .ForEach(i => bufferBlock.Post(i));

            _waitHandle.Wait();
        }
开发者ID:RePierre,项目名称:dot-net-async,代码行数:26,代码来源:SimpleNetworkExample.cs

示例8: ExecutionPipeline

        public ExecutionPipeline(Kernel kernel)
        {
            _kernel = kernel;
            _commandQueue = new BufferBlock<CommandRequest[]>();
            _queryQueue = new BatchBlock<QueryRequest>(MaxConcurrentQueries);

            var transactionHandler = new ActionBlock<object>(t =>
            {
                if (t is QueryRequest[])
                {
                    var queries = t as QueryRequest[];
                    Task[] tasks = queries.Select(q => Task.Factory.StartNew(_ => ExecuteQuery(q), null)).ToArray();
                    Task.WaitAll(tasks);
                }
                else if (t is CommandRequest[])
                {
                    var commands = t as CommandRequest[];
                    foreach (var commandContext in commands)
                    {
                        var result = _kernel.Execute(commandContext.Command);
                        commandContext.Response.Post(result);
                    }
                }

            });
            _commandQueue.LinkTo(transactionHandler);
            _queryQueue.LinkTo(transactionHandler);
            _timer = new Timer(_ => _queryQueue.TriggerBatch());
            _timer.Change(Interval, Interval);
        }
开发者ID:Koulio,项目名称:AsyncOrigoDbSpike,代码行数:30,代码来源:ExecutionPipeline.cs

示例9: HttpNegotiationQueue

        public HttpNegotiationQueue(WebSocketFactoryCollection standards, WebSocketConnectionExtensionCollection extensions, WebSocketListenerOptions options)
        {
            Guard.ParameterCannotBeNull(standards, "standards");
            Guard.ParameterCannotBeNull(extensions, "extensions");
            Guard.ParameterCannotBeNull(options, "options");

            _options = options;
            _extensions = extensions;
            _cancel = new CancellationTokenSource();
            _semaphore = new SemaphoreSlim(options.ParallelNegotiations);
            
            _sockets = new BufferBlock<Socket>(new DataflowBlockOptions()
            {
                BoundedCapacity = options.NegotiationQueueCapacity,
                CancellationToken = _cancel.Token
            });

            _negotiations = new BufferBlock<WebSocketNegotiationResult>(new DataflowBlockOptions()
            {
                BoundedCapacity = options.NegotiationQueueCapacity,
                CancellationToken = _cancel.Token,
            });

            _cancel.Token.Register(_sockets.Complete);
            _cancel.Token.Register(_negotiations.Complete);

            _handShaker = new WebSocketHandshaker(standards, _options);

            Task.Run((Func<Task>)WorkAsync);
        }
开发者ID:papci,项目名称:WebSocketListener,代码行数:30,代码来源:HttpNegotiationQueue.cs

示例10: GreedyJoin3Test

		public void GreedyJoin3Test ()
		{
			var scheduler = new TestScheduler ();
			var block =
				new JoinBlock<int, int, int> (new GroupingDataflowBlockOptions
				{ TaskScheduler = scheduler });
			var source1 =
				new BufferBlock<int> (new DataflowBlockOptions { TaskScheduler = scheduler });
			var source2 =
				new BufferBlock<int> (new DataflowBlockOptions { TaskScheduler = scheduler });
			var source3 =
				new BufferBlock<int> (new DataflowBlockOptions { TaskScheduler = scheduler });
			Assert.IsNotNull (source1.LinkTo (block.Target1));
			Assert.IsNotNull (source2.LinkTo (block.Target2));
			Assert.IsNotNull (source3.LinkTo (block.Target3));

			Assert.IsTrue (source1.Post (1));
			scheduler.ExecuteAll ();

			int i;
			Assert.IsFalse (source1.TryReceive (out i));

			Assert.IsTrue (source2.Post (11));
			Assert.IsTrue (source3.Post (21));
			scheduler.ExecuteAll ();

			Assert.IsFalse (source2.TryReceive (out i));
			Assert.IsFalse (source3.TryReceive (out i));

			Tuple<int, int, int> tuple;
			Assert.IsTrue (block.TryReceive (out tuple));
			Assert.AreEqual (Tuple.Create (1, 11, 21), tuple);
		}
开发者ID:nlhepler,项目名称:mono,代码行数:33,代码来源:GreedyTest.cs

示例11: ProduceLogs

        public void ProduceLogs(int count, int buffSize)
        {
            var bufferOptions = new DataflowBlockOptions() { BoundedCapacity = buffSize };
            var writerOptions = new ExecutionDataflowBlockOptions() { BoundedCapacity = 10, MaxDegreeOfParallelism = 1, MaxMessagesPerTask = 10, SingleProducerConstrained = true };

            LogGenerator g = new LogGenerator();

            var file = new StreamWriter("basic.async.buff.log", false);

            BufferBlock<string> buffer = new BufferBlock<string>(bufferOptions);
            ActionBlock<string> writer = new ActionBlock<string>(s => file.WriteLine(s), writerOptions);

            buffer.LinkTo(writer, new DataflowLinkOptions() { PropagateCompletion = true });

            for (int i = 0; i < count; i++)
            {
                g.Next();

                var line = string.Format(g.FormatStr, g.Param1, g.Param2, g.Param3, g.Param4, g.Param5, g.Param6);
                writer.SendAsync(line).Wait();
            }

            buffer.Complete();

            Completed = writer.Completion.ContinueWith(t => file.Close());
        }
开发者ID:SoftFx,项目名称:PerformancePoC,代码行数:26,代码来源:StringLoggerTest.cs

示例12: Start

        public void Start()
        {
            var sink = new ActionBlock<PageResultMessage>((Action<PageResultMessage>)Sink);
            var source = new BufferBlock<GetPageMessage>();
            var linkOptions = new DataflowLinkOptions {PropagateCompletion = false};

            for (int i = 0; i < 10; i++)
            {
                var options = new ExecutionDataflowBlockOptions
                    {
                        BoundedCapacity = 1
                    };
                var worker = new TransformBlock<GetPageMessage, PageResultMessage>(
                    (Func<GetPageMessage, PageResultMessage>)Worker, options);
                source.LinkTo(worker, linkOptions);
                worker.LinkTo(sink, linkOptions);
            }

            foreach (var url in UrlList.Urls)
            {
                source.Post(new GetPageMessage{ Url = url });
            }
            source.Complete();
            sink.Completion.Wait();
        }
开发者ID:mikehadlow,项目名称:Mike.Spikes,代码行数:25,代码来源:DataflowUrlGetter.cs

示例13: TestDataBroadcaster2

        public async Task TestDataBroadcaster2()
        {
            var random = new Random();
            var buffer = new BufferBlock<int>();
            
            int sum1 = 0;
            int sum2 = 0;
            int sum3 = 0;

            var action1 = new ActionBlock<int>(i => sum1 = sum1 + i);
            var action2 = new ActionBlock<int>(i => sum2 = sum2 + i);
            var action3 = new ActionBlock<int>(i => sum3 = sum3 + i);

            buffer.ToDataflow().LinkToMultiple(new []{action1, action2, action3}.Select(a => a.ToDataflow()).ToArray());
            
            for (int j = 0; j < 1000; j++)
            {
                buffer.Post((int)(random.NextDouble() * 10000));
            }

            buffer.Complete();

            await TaskEx.AwaitableWhenAll(action1.Completion, action2.Completion, action3.Completion);

            Console.WriteLine("sum1 = {0} , sum2 = {1}", sum1, sum2);
            Assert.AreEqual(sum1, sum2);
            Assert.AreEqual(sum1, sum3);
        }
开发者ID:charles-schrupp,项目名称:DataflowEx,代码行数:28,代码来源:TestDataBroadcaster.cs

示例14: ReceiveCompletedTest

		public void ReceiveCompletedTest ()
		{
			var block = new BufferBlock<int> ();
			block.Complete ();
			AssertEx.Throws<InvalidOperationException> (
				() => block.Receive (TimeSpan.FromMilliseconds (1000)));
		}
开发者ID:Profit0004,项目名称:mono,代码行数:7,代码来源:DataflowBlockTest.cs

示例15: MultipleBindingTest

		public void MultipleBindingTest ()
		{
			BufferBlock<int> buffer = new BufferBlock<int> ();
			var evt = new CountdownEvent (10);

			int count = 0;
				
			ActionBlock<int> block = new ActionBlock<int> ((i) => { Interlocked.Decrement (ref count); evt.Signal (); });
			IDisposable bridge = buffer.LinkTo (block);
			for (int i = 0; i < 10; i++)
				Assert.IsTrue (buffer.Post (i));
			evt.Wait ();

			Assert.AreEqual (-10, count);
			count = 0;
			evt.Reset ();
			bridge.Dispose ();

			ActionBlock<int> block2 = new ActionBlock<int> ((i) => { Interlocked.Increment (ref count); evt.Signal (); });
			buffer.LinkTo (block2);
			for (int i = 0; i < 10; i++)
				Assert.IsTrue (buffer.Post (i));
			evt.Wait ();

			Assert.AreEqual (10, count);
		}
开发者ID:carrie901,项目名称:mono,代码行数:26,代码来源:BufferBlockTest.cs


注:本文中的BufferBlock类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。