using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;
 
namespace TDFDemo
{
class Program
{
static void Main(string[] args)
{
new Program().Run();
}
 
private async void Run()
{
var bus = new Bus();
 
// Inline handler
var s1 = bus.Subscribe<Message>(message => Console.WriteLine("Inline Handler 1: {0}", message.Content));
 
// Inline handler factory
var s2 = bus.Subscribe<Message>(() => new MessageHandler().Handle);
 
// Automatic handler subscription
var s3 = bus.Subscribe<Message, MessageHandler>();
 
for (int i = 0; i < 10; i++)
{
await bus.SendAsync(new Message("Message " + i));
}
 
// Unsubscribe the second handler
bus.Unsubscribe(s2);
 
Thread.Sleep(1000);
 
// Cancellation support
 
Console.WriteLine("\nSecond Burst:");
var tokenSource = new CancellationTokenSource();
var token = tokenSource.Token;
 
for (int i = 0; i < 10; i++)
{
await bus.SendAsync(new Message("Message " + i), token);
 
if (i == 5)
{
tokenSource.Cancel();
break;
}
}
 
Console.ReadLine();
}
}
 
public class Message
{
public DateTime TimeStamp { get; private set; }
public string Content { get; private set; }
 
public Message(string content)
{
Content = content;
TimeStamp = DateTime.UtcNow;
}
}
 
public interface IHandle<TMessage>
{
void Handle(TMessage message);
}
 
public class MessageHandler : IHandle<Message>
{
public void Handle(Message message)
{
Console.WriteLine("Message Handler Received: {0}", message.Content);
}
}
 
public class Bus
{
private readonly BroadcastBlock<object> broadcast =
new BroadcastBlock<object>(message => message);
 
private readonly ConcurrentDictionary<Guid, IDisposable> subscriptions
= new ConcurrentDictionary<Guid, IDisposable>();
 
public Task<bool> SendAsync<TMessage>(TMessage message, CancellationToken cancellationToken)
{
return broadcast.SendAsync(message, cancellationToken);
}
 
public Guid Subscribe<TMessage>(Action<TMessage> handlerAction)
{
var handler = new ActionBlock<object>(
message => handlerAction((TMessage)message),
new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 2 }
);
 
var subscription = broadcast.LinkTo(
handler,
new DataflowLinkOptions { PropagateCompletion = true },
message => message is TMessage
);
 
return AddSubscription(subscription);
}
 
public void Unsubscribe(Guid subscriptionId)
{
IDisposable subscription;
if (subscriptions.TryRemove(subscriptionId, out subscription))
{
subscription.Dispose();
}
}
 
private Guid AddSubscription(IDisposable subscription)
{
var subscriptionId = Guid.NewGuid();
subscriptions.TryAdd(subscriptionId, subscription);
return subscriptionId;
}
}
 
public static class BusExtensions
{
public static Task<bool> SendAsync<TMessage>(this Bus bus, TMessage message)
{
return bus.SendAsync<TMessage>(message, CancellationToken.None);
}
 
public static Guid Subscribe<TMessage>(this Bus bus, Func<Action<TMessage>> handlerActionFactory)
{
return bus.Subscribe<TMessage>(message => handlerActionFactory().Invoke(message));
}
 
public static Guid Subscribe<TMessage, THandler>(this Bus bus) where THandler : IHandle<TMessage>, new()
{
return bus.Subscribe<TMessage>(message => new THandler().Handle(message));
}
}
}

tpl demo的更多相关文章

  1. Thinkcmf 二次开发

    一.   创建模板 demo 1 Tpl下创建demo文件-----后台启用新的模板 (网站信息--模板方案) 2 在模板在tpl/demo目录下创建Portal目录,然后在Portal目录下创建in ...

  2. 6个强大的AngularJS扩展应用

    本文链接:http://www.codeceo.com/article/6-angularjs-extension.html本文作者:码农网 – 小峰 AngularJS现在非常热门,是Google推 ...

  3. 迷你版 smarty --模板引擎和解析

    http://blog.ipodmp.com/archives/php-write-a-mini-smarty-template-engine/ 迷你版Smarty模板引擎目录结构如下: ① 要开发一 ...

  4. 从DOM操作看Vue&React的前端组件化,顺带补齐React的demo

    前言 接上文:谈谈我对前端组件化中“组件”的理解,顺带写个Vue与React的demo 上次写完博客后,有朋友反应第一内容有点深,看着迷迷糊糊:第二是感觉没什么使用场景,太过业务化,还不如直接写Vue ...

  5. 谈谈我对前端组件化中“组件”的理解,顺带写个Vue与React的demo

    前言 前端已经过了单兵作战的时代了,现在一个稍微复杂一点的项目都需要几个人协同开发,一个战略级别的APP的话分工会更细,比如携程: 携程app = 机票频道 + 酒店频道 + 旅游频道 + ..... ...

  6. /Home/Tpl/Equipment/rangeIndex.html 里调用魔板

    <pre name="code" class="html">demo:/var/www/DEVOPS# vim ./Home/Tpl/Equipme ...

  7. GatewayWorker+Laravel demo

    GatewayWorker 结合 Laravel 使用的简单案例,重点是在Laravel中使用GatewayClient发送消息 主要流程:GatewayWorker主要负责推送消息给客户端但不接受客 ...

  8. 通过一个demo了解Redux

    TodoList小demo 效果展示 项目地址 (单向)数据流 数据流是我们的行为与响应的抽象:使用数据流能帮我们明确了行为对应的响应,这和react的状态可预测的思想是不谋而合的. 常见的数据流框架 ...

  9. 很多人很想知道怎么扫一扫二维码就能打开网站,就能添加联系人,就能链接wifi,今天说下这些格式,明天做个demo

    有些功能部分手机不能使用,网站,通讯录,wifi基本上每个手机都可以使用. 在看之前你可以扫一扫下面几个二维码先看看效果: 1.二维码生成 网址 (URL) 包含网址的 二维码生成 是大家平时最常接触 ...

随机推荐

  1. 2假动作,数据缓冲,CCEaseExponential,CCEaseElastic,CCEaseBounce,CCCallFunc,funcNCallBack,funcNDCallBack,funcO

     1 缓冲动作 watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdG90b3R1enVvcXVhbg==/font/5a6L5L2T/fontsize/4 ...

  2. CLOSE_WAIT状态的原因与解决方法 --转

    转自:http://blog.chinaunix.net/uid-20357359-id-1963662.html 这个问题之前没有怎么留意过,是最近在面试过程中遇到的一个问题,面了两家公司,两家公司 ...

  3. Debugging to Understand Finalizer--reference

    This post is covering one of the Java built-in concepts called Finalizer. This concept is actually b ...

  4. tarball文件安装的大概流程

    ./configure这个步骤就是在创建 Makefile 这个文件罗!通常程序开发者会写一支 scripts 来检查你的 Linux 系统.相关的软件属性等等,这个步骤相当的重要, 因为未来你的安装 ...

  5. ie6的兼容总结

    ie6的兼容处理总结 1.透明背景图: .timer { _filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='my.png ...

  6. 鸭子类型duck typing(动态)

    在程序设计中,鸭子类型(duck typing)是动态类型的一种风格.在这种风格中,一个对象有效的语义,不是由继承自特定的类或实现特定的接口,而是由当前方法和属性的集合决定.这个概念的名字来源于由Ja ...

  7. android 中 系统日期时间的获取

    import    java.text.SimpleDateFormat; SimpleDateFormat    formatter    =   new    SimpleDateFormat   ...

  8. MySQL之DML语句(insert update delete)

    DML主要针对数据库表对象的数据而言的,一般DML完成: 插入新数据 修改已添加的数据 删除不需要的数据 1.insert into插入语句 //主键自增可以不插入,所以用null代替 ); //指定 ...

  9. Servlet & JSP - Decorating Requests and Responses

    Servlet API 提供了四个包装类:ServletRequestWrapper.ServletResponseWrapper.HttpServletRequestWrapper.HttpServ ...

  10. ASP与ASP.NET转换Session数据桥的应用

    背景: 现有公司的产品OA是采用ASP早先的技术开发,需要与目前最新的ASP.NET产品进行数据交互的应用.现有的ASP应用程序往往采用“ASP Sessions”,这是一种经典的ASP内置模式,即允 ...