我有一个
我该怎么做才能防止块以这种方式消耗
编辑:以下是说明问题的示例程序:
TransformManyBlock
块,其设计如下:
- 输入:文件路径
- 输出:文件内容的IEnumerable,每行一个
BoundedCapacity
设置为非常低的值(例如1)。然而,该块显然会贪婪地迭代IEnumerable,这会消耗计算机上所有可用的内存,使每个进程停滞不前。该块的输出计数继续无限增加,直到我终止进程。我该怎么做才能防止块以这种方式消耗
IEnumerable
?编辑:以下是说明问题的示例程序:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;
class Program
{
static IEnumerable<string> GetSequence(char c)
{
for (var i = 0; i < 1024 * 1024; ++i)
yield return new string(c, 1024 * 1024);
}
static void Main(string[] args)
{
var options = new ExecutionDataflowBlockOptions() { BoundedCapacity = 1 };
var firstBlock = new TransformManyBlock<char, string>(c => GetSequence(c), options);
var secondBlock = new ActionBlock<string>(str =>
{
Console.WriteLine(str.Substring(0, 10));
Thread.Sleep(1000);
}, options);
firstBlock.LinkTo(secondBlock);
firstBlock.Completion.ContinueWith(task =>
{
if (task.IsFaulted) ((IDataflowBlock) secondBlock).Fault(task.Exception);
else secondBlock.Complete();
});
firstBlock.Post('A');
firstBlock.Complete();
for (; ; )
{
Console.WriteLine("OutputCount: {0}", firstBlock.OutputCount);
Thread.Sleep(3000);
}
}
}
如果您使用的是64位计算机,请确保在Visual Studio中清除“首选32位”选项。我的电脑上有16GB的RAM,这个程序会立即消耗所有可用的字节。