我想知道是否可以优化以下代码以更快地执行。我目前似乎在一个非常简单的数据流结构上每秒最多可以处理 140 万条简单消息。我知道这个示例过程同步传递/转换消息,但是,我目前测试 TPL Dataflow 作为我自己的基于任务和并发集合的自定义解决方案的可能替代品。我知道术语“并发”已经建议我并行运行,但为了当前的测试目的,我通过同步在自己的解决方案上推送消息,每秒大约有 510 万条消息。我在这里缺少什么,我读到 TPL 数据流被推为高吞吐量、低延迟的解决方案,但到目前为止我必须忽略性能调整。谁能指出我正确的方向?
class TPLDataFlowExperiments
{
public TPLDataFlowExperiments()
{
var buf1 = new BufferBlock<int>();
var transform = new TransformBlock<int, string>(t =>
{
return "";
});
var action = new ActionBlock<string>(s =>
{
//Thread.Sleep(100);
//Console.WriteLine(s);
});
buf1.LinkTo(transform);
transform.LinkTo(action);
//Propagate all Completions down the flow
buf1.Completion.ContinueWith(t =>
{
transform.Complete();
transform.Completion.ContinueWith(u =>
{
action.Complete();
});
});
Stopwatch watch = new Stopwatch();
watch.Start();
int cap = 10000000;
for (int i = 0; i < cap; i++)
{
buf1.Post(i);
}
//Mark Buffer as Complete
buf1.Complete();
action.Completion.ContinueWith(t =>
{
watch.Stop();
Console.WriteLine("All Blocks finished processing");
Console.WriteLine("Units processed per second: " + cap / watch.ElapsedMilliseconds * 1000);
});
Console.ReadLine();
}
}