发生一个或多个错误。(抛出类型 'System.OutOfMemoryException' 的异常。



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

错误:

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)

代码:

public async Task<List<string>> ListS3ObjectsAsync(string bucketName, string filestoDwnld, IAmazonS3 client)
{
//int fileCount = 0;
List<string> pdfFiles = new List<string>();

ListObjectsRequest request = new ListObjectsRequest
{
BucketName = bucketName,
Prefix = filestoDwnld,
};
ListObjectsResponse response = await client.ListObjectsAsync(request);
do
{
foreach (S3Object entry in response.S3Objects)
pdfFiles.Add(entry.Key);
if (response.IsTruncated)
{
request.Marker = response.NextMarker;
}
else
request = null;

} while (request != null);
return pdfFiles;
}

我也尝试过增加列表容量,但这也无济于事。请协助。

OutOfMemoryException的原因是在响应时触发的无限循环中。在这种情况下,请求永远不会设置为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);

通过这种方式,在第一个循环之后,您再次从指向NextMarker的服务后端询问一组新的元素,最终您将达到IsTruncated将为false的点,从而结束循环

最新更新