C# 发生了一个或多个错误。(引发了类型为“System.OutOfMemoryException”的异常。)

C# 发生了一个或多个错误。(引发了类型为“System.OutOfMemoryException”的异常。),c#,aws-lambda,C#,Aws Lambda,当通过Lambda函数创建超过30k个项目的列表时,我遇到了下面提到的错误 错误: System.Collections.Generic.List`1.set_Capacity(Int32 value) at System.Collections.Generic.List`1.EnsureCapacity(Int32 min) at System.Collections.Generic.List`1.AddWithResize(T item) at at System.Collections.

当通过Lambda函数创建超过30k个项目的列表时,我遇到了下面提到的错误

错误:

System.Collections.Generic.List`1.set_Capacity(Int32 value) at System.Collections.Generic.List`1.EnsureCapacity(Int32 min) at System.Collections.Generic.List`1.AddWithResize(T item) at

at System.Collections.Generic.List`1.set_Capacity(Int32 value)
   at System.Collections.Generic.List`1.EnsureCapacity(Int32 min)
   at System.Collections.Generic.List`1.AddWithResize(T item)
   at AWSLambda3.Function.ListS3ObjectsAsync(String bucketName, String filestoDwnld, IAmazonS3 client)
代码:


我也尝试过增加列表容量,但也没有什么帮助。请协助。

OutOfMemoryException的原因是在response.IsTruncated==true时触发的无限循环中。在这种情况下,请求永远不会设置为null,循环也不会停止。代码将重新启动一个新循环,再次将相同的元素集加载到列表pdfFiles中,依此类推,直到没有更多内存为止

我不知道您的服务后端是如何工作的,但我可以想象您只需要更改一行代码,将请求插入到循环中的服务调用中

do
{
    // This inside the loop will be executed at least one time and 
    // eventually again until the IsTruncated property is set to true.
    ListObjectsResponse response = await client.ListObjectsAsync(request);

    foreach (S3Object entry in response.S3Objects)
        pdfFiles.Add(entry.Key);

    if (response.IsTruncated)
    {
        request.Marker = response.NextMarker;
    }
    else
        request = null;
    
} while (request != null);

这样,,在第一个循环之后,您再次从服务后端请求指向下一个Marker的一组新元素,最终您将到达IsTruncated为false的点结束循环

OutOfMemoryException的原因是在无限循环中,当response.IsTruncated==true时触发。在这种情况下,请求为true从不设置为null,循环不会停止。代码将重新启动一个新循环,再次将相同的元素集加载到列表pdfFiles中,依此类推,直到没有更多内存为止

我不知道您的服务后端是如何工作的,但我可以想象您只需要更改一行代码,将请求插入到循环中的服务调用中

do
{
    // This inside the loop will be executed at least one time and 
    // eventually again until the IsTruncated property is set to true.
    ListObjectsResponse response = await client.ListObjectsAsync(request);

    foreach (S3Object entry in response.S3Objects)
        pdfFiles.Add(entry.Key);

    if (response.IsTruncated)
    {
        request.Marker = response.NextMarker;
    }
    else
        request = null;
    
} while (request != null);

这样,在第一次循环之后,您再次从服务后端请求指向下一个Marker的一组新元素,最终您将到达一个点,在该点上IsTruncated将为false,结束循环

存储桶的项目数不超过32k,所以它不可能进入无限循环,但这并不意味着对client.ListObjectsAsync的调用在一次调用中返回所有32K对象。如果它只返回1K个对象并将IsTruncated设置为true,该怎么办?无论如何,一个简单的调试会话会告诉你真相,我现在明白你的意思了。AWS施加了一个限制,一次返回的对象不超过1000个。bucket的项数不超过32k,因此它不可能进入无限循环。但这并不意味着对client.ListObjectsAsync的调用在一次调用中返回所有32k对象。如果它只返回1K个对象并将IsTruncated设置为true,该怎么办?无论如何,一个简单的调试会话会告诉你真相,我现在明白你的意思了。AWS有一个限制,一次返回的对象不超过1000个。