BatchBlock提供了能够把多个单个的数据组合起来处理的功能,如上图。应对有些需求需要固定多个数据才能处理的问题。在构造函数中需要制定多少个为一个Batch,一旦它收到了那个数量的数据后,会打包放在它的OutputQueue中。当BatchBlock被调用Complete( )告知Post数据结束的时候,会把InputQueue中余下的数据打包放入OutputQueue中等待处理,而不管InputQueue中的数据量是不是满足构造函数的数量。【代码地址-BatchBlock1项目】
public static BatchBlock<int> batchBlock = new BatchBlock<int>(3);public const string DateFormate = "yyyy-MM-dd HH:mm:ss.fff";public Form1()
{InitializeComponent();}static int clickCount = 0;private void btnPost_Click(object sender, EventArgs e){try
{batchBlock.Post(++clickCount);Console.WriteLine($"{DateTime.Now.ToString(DateFormate)} " +
$"Post 后 Out:{batchBlock.OutputCount} ClickCount:{clickCount}");
}catch (Exception ex)
{Console.WriteLine(ex.Message);}}private void btnRecive_Click(object sender, EventArgs e){Console.WriteLine($"{DateTime.Now.ToString(DateFormate)} " +
$"Recive前 Out:{batchBlock.OutputCount}");
int[] data;
//int[] data = batchBlock.Receive();
bool ret = batchBlock.TryReceive(out data);//输出时为集合类型,将Target队列中的数据N一次性放入到Source队列。string str = "";
if (ret == true){foreach (int item in data){str = str + item.ToString() + ",";
}}Console.WriteLine($"{DateTime.Now.ToString(DateFormate)} " +
$"Recive后 Out:{batchBlock.OutputCount} 【{str.TrimEnd(',')}】 {ret}");
batchBlock.Complete();}