TPL 之五 JoinBlock

    JoinBlock一看名字就知道是需要和两个或两个以上的Source Block相连接的。它的作用就是等待一个数据组合,这个组合需要的数据都到达了,它才会处理数据,并把这个组合作为一个Tuple传递给目标Block。举个例子,如果定义了JoinBlock<int, string>类型,那么JoinBlock内部会有两个ITargetBlock,一个接收int类型的数据,一个接收string类型的数据。那只有当两个ITargetBlock都收到各自的数据后,才会放到JoinBlock的OutputQueue中,输出。【代码地址-JoinBlock1】

image

public static JoinBlock<int, string> joinBlock = new JoinBlock<int, string>();
public const string DateFormat = "yyyy-MM-dd HH:mm:ss.fff";
public Form1()
{
    InitializeComponent();
}
private void btnPost1_Click(object sender, EventArgs e)
{
    joinBlock.Target1.Post(10);
    Console.WriteLine($"{DateTime.Now.ToString(DateFormat)} Out:{joinBlock.OutputCount}");
}
private void btnPost2_Click(object sender, EventArgs e)
{
    joinBlock.Target2.Post("20");
    Console.WriteLine($"{DateTime.Now.ToString(DateFormat)} Out:{joinBlock.OutputCount}");
}
private void btnRecevie_Click(object sender, EventArgs e)
{
    Tuple<int, string> tuple;
    bool ret = joinBlock.TryReceive(out tuple);
    if (ret == true)
    {
        Console.WriteLine($"{DateTime.Now.ToString(DateFormat)} Out:{joinBlock.OutputCount} 【{tuple.Item1} {tuple.Item2}】 {ret}");
    }

}


posted @ 2020-08-11 16:00  李华丽  阅读(103)  评论(0编辑  收藏  举报
AmazingCounters.com