Пример #1
0
        public void UC01_OneAsyncConsumers()
        {
            // Create a BufferBlock<byte[]> object. This object serves as the
            // target block for the producer and the source block for the consumer.
            var buffer = new System.Threading.Tasks.Dataflow.BufferBlock <byte[]>();
            var Dpc    = new DataflowProducerConsumer();

            // Start the consumer. The Consume method runs asynchronously.
            var consumer = Dpc.ConsumeAsync(buffer);

            // Post source data to the dataflow block.
            Dpc.Produce(buffer);

            // Wait for the consumer to process all data.
            consumer.Wait();

            // Print the count of bytes processed to the console.
            Console.WriteLine("Processed {0} bytes.", consumer.Result);
        }
Пример #2
0
        public void UC03_DataflowReadWriteInt()
        {
            // Create a BufferBlock<int> object.
            var bufferBlock = new System.Threading.Tasks.Dataflow.BufferBlock <int>();
            var Drw         = new DataflowReadWrite();

            // Post several messages to the block.
            for (int i = 0; i < 3; i++)
            {
                bufferBlock.Post(i);
            }

            // Receive the messages back from the block.
            for (int i = 0; i < 3; i++)
            {
                Console.WriteLine(bufferBlock.Receive());
            }

            // Post more messages to the block.
            for (int i = 0; i < 3; i++)
            {
                bufferBlock.Post(i);
            }

            // TryReceive the messages back from the block.
            int value;

            while (bufferBlock.TryReceive(out value))
            {
                Console.WriteLine(value);
            }

            // Write to and read from the message block concurrently.
            var post01 = Task.Run(() =>
            {
                bufferBlock.Post(0);
                bufferBlock.Post(1);
            });
            var receive = Task.Run(() =>
            {
                for (int i = 0; i < 3; i++)
                {
                    Console.WriteLine(bufferBlock.Receive());
                }
            });
            var post2 = Task.Run(() =>
            {
                bufferBlock.Post(2);
            });

            Task.WaitAll(post01, receive, post2);

            /* Sample output:
             * 2
             * 0
             * 1
             */

            // Demonstrate asynchronous dataflow operations.
            Drw.AsyncSendReceive(bufferBlock).Wait();
        }