CloudBlockBlob的OpenReadAsync和DownloadFromStreamAsync功能之间的区别

per*_*713 6 azure azure-storage-blobs

Azure blob存储有什么区别OpenReadAsyncDownloadToStreamAsync功能CloudBlockBlob?在谷歌搜索但无法找到答案.

Jam*_*SFT 15

OpenReadAsync和DownloadToStreamAsync都可以启动异步操作以检索blob流.根据我的测试,您可以通过以下部分更好地了解它们:  

基本概念

DownloadToStreamAsync:启动异步操作以将blob的内容下载到流.

OpenReadAsync:启动异步操作以将blob的内容下载到流中.  

用法

a)DownloadToStreamAsync

示例代码:

using (var fs = new FileStream(<yourLocalFilePath>, FileMode.Create))
{
    await blob.DownloadToStreamAsync(fs);
}
Run Code Online (Sandbox Code Playgroud)

  b)OpenReadAsync

示例代码:

//Set buffer for reading from a blob stream, the default value is 4MB.
blob.StreamMinimumReadSizeInBytes=10*1024*1024; //10MB
using (var blobStream = await blob.OpenReadAsync())
{
    using (var fs = new FileStream(localFile, FileMode.Create))
    {   
       await blobStream.CopyToAsync(fs);
    }
}
Run Code Online (Sandbox Code Playgroud)

通过Fiddler捕获网络请求

a)DownloadToStreamAsync

在此输入图像描述 在此输入图像描述   b)OpenReadAsync

在此输入图像描述 在此输入图像描述

  根据以上所述,DownloadToStreamAsync只发送一个获取请求以检索blob流,而OpenReadAsync根据您设置的"Blob.StreamMinimumReadSizeInBytes"或默认值发送多个请求来检索blob流.

  • 大文件有问题吗? (4认同)

Eir*_*k W 5

DownloadToStreamAsync和 的区别在于OpenReadAsyncDownloadToStreamAsync会在返回之前将 blob 的内容下载到流中,但OpenReadAsync在流被消耗完之前不会触发下载。

例如,如果使用它从 ASP.NET core 服务返回文件流,则应该使用OpenReadAsync而不是DownloadToStreamAsync

示例DownloadToStreamAsync(在这种情况下不推荐):

Stream target = new MemoryStream(); // Could be FileStream
await blob.DownloadToStreamAsync(target); // Returns when streaming (downloading) is finished. This requires the whole blob to be kept in memory before returning!
_logger.Log(LogLevel.Debug, $"DownloadToStreamAsync: Length: {target.Length} Position: {target.Position}"); // Output: DownloadToStreamAsync: Length: 517000 Position: 517000
target.Position = 0; // Rewind before returning Stream:
return File(target, contentType: blob.Properties.ContentType, fileDownloadName: blob.Name, lastModified: blob.Properties.LastModified, entityTag: null);
Run Code Online (Sandbox Code Playgroud)

示例OpenReadAsync(在本例中推荐):

// Do NOT put the stream in a using (or close it), as this will close the stream before ASP.NET finish consuming it.
Stream blobStream = await blob.OpenReadAsync(); // Returns when the stream has been opened
_logger.Log(LogLevel.Debug, $"OpenReadAsync: Length: {blobStream.Length} Position: {blobStream.Position}"); // Output: OpenReadAsync: Length: 517000 Position: 0
return File(blobStream, contentType: blob.Properties.ContentType, fileDownloadName: blob.Name, lastModified: blob.Properties.LastModified, entityTag: null);
Run Code Online (Sandbox Code Playgroud)