c# - 将 Azure.AsyncPageable<BlobItem> 转换为 List<BlobItem>

标签 c# azure asynchronous azure-functions azure-blob-storage

我正在从 Azure Blob 存储容器中检索数十万个 Blob。基于检索,我正在计算检索时间,需要将 blob 转换为可读格式,并且需要获取结果中的 blob 项目计数。因此,我检索 blob 并将其转换为 List< BlobItem > ,如下所述。现在的问题是,当我使用方法 GetBlobsAsync() 检索容器中可用的所有 Blob 时,需要几毫秒才能从存储容器中获取所有 Blob 项。但是,当我使用 blobItems.ToListAsync() 将 Blob 项转换为 List< BlobItem > 时,需要 5-10 分钟才能完成。

var watch = System.Diagnostics.Stopwatch.StartNew();
BlobContainerClient client = new BlobContainerClient(connectionString, containerName);
var blobItems =  client.GetBlobsAsync(); //This line take 60-80 milli seconds to get all blobs
var blobList =await blobItems.ToListAsync(); //This line takes 5-10mins to complete
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
return new OkObjectResult(blobList);

仅在转换期间,完成所有 blob 所需的时间太长。即使我尝试使用 Foreach 循环进行相同的操作,也需要很长时间(5-10 分钟)才能将整个数据作为可读数据获取。需要在几毫秒内将 Azure.AsynPageable 转换为其他可读格式的帮助。如果有其他方法,我们也能达到同样的效果。谢谢

最佳答案

Now the problem is, when I retrieve all the blobs available in the container using the method GetBlobsAsync(), it is taking few milliseconds to get all the blob items from the storage container. But when am converting the blob items into List< BlobItem > using blobItems.ToListAsync(), it is taking 5-10 minutes to complete it.

这不是正在发生的事情。 GetBlobsAsync 返回一个 AsyncPageable。它实际上并没有获取 blob 项。仅当您迭代结果时才会发生这种情况,如 the docs 中所述。

The GetBlobsAsync(BlobTraits, BlobStates, String, CancellationToken) operation returns an async sequence of blobs in this container. Enumerating the blobs may make multiple requests to the service while fetching all the values.

在您的情况下,代码 await blobItems.ToListAsync(); 枚举 blob,因此这将花费大部分时间。

Got your point. But await blobItems.ToListAsync(); is taking long time to process the data retrieval. Is there any way to speedup the retrieve process by using any parallel programing process or any other way?

如果您有虚拟文件夹结构,则可以使用 GetBlobsAsync 方法的 prefix 参数批量获取 Blob 项目,如下所示:

async Task DownloadBlobsAsync(BlobContainerClient client)
{
    var blobItemLists = await Task.WhenAll(new[] {
        DownloadBlobsByPrefix("folder1"),
        DownloadBlobsByPrefix("folder2")
    });
    
    var  blobItems = blobItemLists.SelectMany(items => items);
}

async Task<List<BlobItem>> DownloadBlobsByPrefix(string prefix)
{
    var blobItems = client.GetBlobsAsync(prefix: prefix);
    return await blobItems.ToListAsync();
}

但是您需要进行测量,看看这是否具有您想要的效果。此外,您还需要考虑要使用的正确前缀集。

关于c# - 将 Azure.AsyncPageable<BlobItem> 转换为 List<BlobItem>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74837672/

相关文章:

c# - 从 WPF/XAML 中的字符串末尾清除空格

C# .Net Core 依赖注入(inject),向构造函数注入(inject)多个参数

c# - 当存在单个对象的转换方法时,如何创建通用方法来转换对象列表?

azure - IoT 中心 - 如何注册生命周期事件 - 断开连接和连接?

javascript - 异步函数调用后从工厂返回 Angular $resource

c# - MVC 5 模型绑定(bind)器覆盖

c# - Azure SuggestAsync 映射到 POCO

azure - Hive 外部表 - 删除表/分区并删除数据

javascript - 为什么我从 repl.it 上的这段代码中看到 "Promise { <pending> }"?

javascript - 在函数内部修改变量后,为什么变量未更改? -异步代码引用