How to: 使用 数据流 实现生产者-消费者模式
producer把消息发送到消息块,consumer从块读取消息。
安装:
- Install-Package Microsoft.Tpl.Dataflow
- using System.Threading.Tasks.Dataflow;
解释:
Produce方法随机生成字节,并Post到ITargetBlock对象;
Consumer方法从ISourceBlock对象读取字节;
可以使用BufferBlock来同时扮演源和目标对象。
Post():同步发送消息。
Complete():表明当前块(source block)已经没有数据更多的数据了。
Consumer方法使用await和async操作符异步地计算总的字节数。
OutputAvailableAsync():从source block收到一个通知(接收到Complete的通知),表明没有更多的数据可用。
- public
static
class DataflowProducerConsumer - {
- // Demonstrates the production end of the producer and consumer pattern.
- static
void Produce(ITargetBlock<byte[]> target) - {
- Random rand = new Random();
- // In a loop, fill a buffer with random data and
- // post the buffer to the target block.
- for (int i = 0; i < 100; i++)
- {
- // Create an array to hold random byte data.
- byte[] buffer = new
byte[1024]; - // Fill the buffer with random bytes.
- rand.NextBytes(buffer);
- // Post the result to the message block.
- target.Post(buffer);
- }
- // Set the target to the completed state to signal to the consumer
- // that no more data will be available.
- target.Complete();
- }
- // Demonstrates the consumption end of the producer and consumer pattern.
- static async Task<int> ConsumeAsync(ISourceBlock<byte[]> source)
- {
- // Initialize a counter to track the number of bytes that are processed.
- int bytesProcessed = 0;
- // Read from the source buffer until the source buffer has no
- // available output data.
- while (await source.OutputAvailableAsync())
- {
- byte[] data = source.Receive();
- // Increment the count of bytes received.
- bytesProcessed += data.Length;
- }
- return bytesProcessed;
- }
- static
void Run(string[] args) - {
- // 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 BufferBlock<byte[]>();
- // Start the consumer. The Consume method runs asynchronously.
- var consumer = ConsumeAsync(buffer);
- // Post source data to the dataflow block.
- 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);
- }
- }
参考:https://msdn.microsoft.com/en-us/library/hh228601(v=vs.110).aspx
How to: 使用 数据流 实现生产者-消费者模式的更多相关文章
- java多线程 生产者消费者模式
package de.bvb; /** * 生产者消费者模式 * 通过 wait() 和 notify() 通信方法实现 * */ public class Test1 { public static ...
- LabVIEW之生产者/消费者模式--队列操作 彭会锋
LabVIEW之生产者/消费者模式--队列操作 彭会锋 本文章主要是对学习LabVIEW之生产者/消费者模式的学习笔记,其中涉及到同步控制技术-队列.事件.状态机.生产者-消费者模式,这几种技术在在本 ...
- 转:Task任务调度实现生产者消费者模式 (个人理解后文)
纯属个人愚见.欢迎加入反驳(PiDou). 1.前文大致就是,利用Queue配置的一个TaskFactory任务调度器.实现生产者消费者模式的例子..首先我就试了 第一种 FIFO(先进先出)的配置. ...
- Lucene.net站内搜索—4、搜索引擎第一版技术储备(简单介绍Log4Net、生产者消费者模式)
目录 Lucene.net站内搜索—1.SEO优化 Lucene.net站内搜索—2.Lucene.Net简介和分词Lucene.net站内搜索—3.最简单搜索引擎代码Lucene.net站内搜索—4 ...
- MVC异常日志生产者消费者模式记录(异常过滤器)
生产者消费者模式 定义自己的异常过滤器并注册 namespace Eco.Web.App.Models { public class MyExceptionAttribute : HandleErro ...
- 转:Task任务调度实现生产者消费者模式
我们经常会遇到生产者消费者模式,比如前端各种UI操作事件触发后台逻辑等.在这种典型的应用场景中,我们可能会有4个业务处理逻辑(下文以P代表生产者,C代表消费者): 1. FIFO(先进先出) ...
- .net学习之多线程、线程死锁、线程通信 生产者消费者模式、委托的简单使用、GDI(图形设计接口)常用的方法
1.多线程简单使用(1)进程是不执行代码的,执行代码的是线程,一个进程默认有一个线程(2)线程默认情况下都是前台线程,要所有的前台线程退出以后程序才会退出,进程里默认的线程我们叫做主线程或者叫做UI线 ...
- 使用BlockingQueue的生产者消费者模式
BlockingQueue很好的解决了多线程中,如何高效安全“传输”数据的问题.通过这些高效并且线程安全的队列类,为我们快速搭建高质量的多线程程序带来极大的便利.使用场景. 首先它是一个队列,而一个队 ...
- Java设计模式—生产者消费者模式(阻塞队列实现)
生产者消费者模式是并发.多线程编程中经典的设计模式,生产者和消费者通过分离的执行工作解耦,简化了开发模式,生产者和消费者可以以不同的速度生产和消费数据.这篇文章我们来看看什么是生产者消费者模式,这个问 ...
随机推荐
- ios 横竖屏通知
屏幕切换时,会发送一个通知.只要注册一个通知: [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(do ...
- 奶牛健美操(codevs 3279)
题目描述 Description Farmer John为了保持奶牛们的健康,让可怜的奶牛们不停在牧场之间 的小路上奔跑.这些奶牛的路径集合可以被表示成一个点集和一些连接 两个顶点的双向路,使得每对点 ...
- Codeforces Round #327 (Div. 2)B(逻辑)
B. Rebranding time limit per test 2 seconds memory limit per test 256 megabytes input standard input ...
- android DisplayMetrics 获取屏幕分辨率
Android 提供DisplayMetircs 类可以很方便的获取分辨率.下面介绍 DisplayMetics 类: Andorid.util 包下的DisplayMetrics 类提供了一种关于显 ...
- map find 是线程安全的吗
测试环境gcc4.8.2 iterator find ( const key_type& k ); const_iterator find ( const key_type& ...
- **代码审查:Phabricator命令行工具Arcanist的基本用法
Phabricator入门手册 http://www.oschina.net/question/191440_125562 Pharicator是FB的代码审查工具,现在我所在的团队也使用它来进行代码 ...
- Shell编程基础教程3--Shell输入与输出
3.Shell输入与输出 3.1.echo echo命令可以显示文本行或变量,或者把字符串输出到文件 echo [option] string ...
- 开个坑, 写个阿里云开放储存服务(OSS)的C++版SDK以及客户端
这应该是继我研究手册QQ协议后的第2个稍微正式一点的网络程序, 不只是Scoket套接字编程, 还涉及到更多的HTTP协议知识! 阿里云开放储存服务OSS官方已经提供了不少SDK, 包括PHP/Pyt ...
- gcc参数-l传递顺序错误导致`undefined reference'的一点小结
刚才编译一个pthread的单文件程序, 使用的命令行是: gcc -o thread1 -lpthread thread1.c 结果报错: $ gcc -o thread1 -lpthread th ...
- 使用.NET Framework的配置文件app.config
在一般的项目中,为了使你的代码更加灵活,更方便调整,减少不必要的hard code,我们都在config中添加许多配置信息,一般可以选择.NET自带的配置文件形式app.config或者web项目中的 ...