Why does it hang indefinitely?

寵の児 提交于 2021-02-17 07:07:58

问题


I wonder why is the reason why this code never finishes its execution.

It makes use of MoreLinq

void Main()
{
    var values = MoreEnumerable.Random(1, 200);
    var filtered = MyMethod(values)
    .Take(2)
    .Dump();
}

public IEnumerable<int> MyMethod(IEnumerable<int> source) 
{
    return source
    .Select(x => new[] { x })
    .Aggregate((a, b) => new[] { a.Last() + b.First()});
}

回答1:


Because MoreEnumerable.Random(1, 200) returns an infinite sequence and the .Aggregate statement in MyMethod is trying to enumerate the whole sequence.

If I understand correctly what you are trying to do, moving Take to MyMethod may work:

public static IEnumerable<int> MyMethod(IEnumerable<int> source)
{
    return source
    .Select(x => new[] { x })
    .Take(2)
    .Aggregate((a, b) => new[] { a.Last() + b.First() });
}



回答2:


I find out that this method(.Random(1, 200)) returns an infinite sequence of random integers using the standard .NET random number generator. Documentation




回答3:


MoreEnumerable.Random enumerate an infinite list of random integers, that's why.

You have to replace

var values = MoreEnumerable.Random(1, 200);

by a finite list:

var values = MoreEnumerable.Random(1, 200).Take(100);

For reason I do not know yet, the Aggregation seems to take the whole list, despite you put .Take(2) two lines after.



来源:https://stackoverflow.com/questions/66198483/why-does-it-hang-indefinitely

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!