当某些并行进程执行繁重的工作时,数据流会阻塞
Dataflow blocks when some parallel process does a heavy job
我正在尝试了解 TPL 数据流。
我有两个块 inputBlock och nextBlock.
inputBlock 使用 MaxDegreeOfParallelism = 2。
我有这种情况,它可能需要不同的时间来完成并行作业。我不希望由于某些并行作业需要很长时间才能完成而导致数据流停止。
我只是希望每个并行作业从队列中取出一个项目并处理它,然后将它传递给下一个块。
当第一个块中的一个并行作业 "inputBlock" 进入睡眠状态或执行繁重的工作时,我永远不会到达 nextBlock。
internal class Program
{
private static bool _sleep = true;
private static void Main(string[] args)
{
var inputBlock = new TransformBlock<string, string>(
x =>
{
if (_sleep)
{
_sleep = false;
Console.WriteLine("First thread sleeping");
Thread.Sleep(5000000);
}
Console.WriteLine("Second thread running");
return x;
},
new ExecutionDataflowBlockOptions {MaxDegreeOfParallelism = 2}); //1
var nextBlock = new TransformBlock<string, string>(
x =>
{
Console.WriteLine(x);
return x;
}); //2
inputBlock.LinkTo(nextBlock, new DataflowLinkOptions {PropagateCompletion = true});
for (var i = 0; i < 100; i++)
{
input.Post(i.ToString());
}
input.Complete();
Console.ReadLine();
}
}
}
答案是使用 EnsureOrdered = false。
新的 ExecutionDataflowBlockOptions {MaxDegreeOfParallelism = 2, EnsureOrdered = false});
我正在尝试了解 TPL 数据流。 我有两个块 inputBlock och nextBlock.
inputBlock 使用 MaxDegreeOfParallelism = 2。 我有这种情况,它可能需要不同的时间来完成并行作业。我不希望由于某些并行作业需要很长时间才能完成而导致数据流停止。 我只是希望每个并行作业从队列中取出一个项目并处理它,然后将它传递给下一个块。
当第一个块中的一个并行作业 "inputBlock" 进入睡眠状态或执行繁重的工作时,我永远不会到达 nextBlock。
internal class Program
{
private static bool _sleep = true;
private static void Main(string[] args)
{
var inputBlock = new TransformBlock<string, string>(
x =>
{
if (_sleep)
{
_sleep = false;
Console.WriteLine("First thread sleeping");
Thread.Sleep(5000000);
}
Console.WriteLine("Second thread running");
return x;
},
new ExecutionDataflowBlockOptions {MaxDegreeOfParallelism = 2}); //1
var nextBlock = new TransformBlock<string, string>(
x =>
{
Console.WriteLine(x);
return x;
}); //2
inputBlock.LinkTo(nextBlock, new DataflowLinkOptions {PropagateCompletion = true});
for (var i = 0; i < 100; i++)
{
input.Post(i.ToString());
}
input.Complete();
Console.ReadLine();
}
}
}
答案是使用 EnsureOrdered = false。
新的 ExecutionDataflowBlockOptions {MaxDegreeOfParallelism = 2, EnsureOrdered = false});