我想知道以下代码是否能被优化以提高执行速度。我目前似乎在一个相当简单的数据流结构上最多只能达到每秒140万个简单消息。我知道这个示例进程同步地传递/转换消息,但是我目前正在测试TPL Dataflow作为我的自定义任务和并发集合解决方案的可能替代品。我知道“并发”这个术语已经表明我要并行运行事物,但是为了进行当前的测试目的,我使用自己的解决方案同步地推送消息,我达到了每秒510万条消息。我错过了什么吗?我读到TPL Dataflow被推作高吞吐量、低延迟的解决方案,但到目前为止,我肯定忽略了性能调整。请问有谁能指导我正确的方向?
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();
}
}