【发布时间】:2013-08-15 13:45:00
【问题描述】:
我正在尝试使用 .NET 4.5 async & await 实现 完全异步 blob 下载。
假设整个 blob 可以同时放入内存中,并且我们希望将其保存在 string 中。
代码:
public async Task<string> DownloadTextAsync(ICloudBlob blob)
{
using (Stream memoryStream = new MemoryStream())
{
IAsyncResult asyncResult = blob.BeginDownloadToStream(memoryStream, null, null);
await Task.Factory.FromAsync(asyncResult, (r) => { blob.EndDownloadToStream(r); });
memoryStream.Position = 0;
using (StreamReader streamReader = new StreamReader(memoryStream))
{
// is this good enough?
return streamReader.ReadToEnd();
// or do we need this?
return await streamReader.ReadToEndAsync();
}
}
}
用法:
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageAccountConnectionString"));
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference("container1");
CloudBlockBlob blockBlob = container.GetBlockBlobReference("blob1.txt");
string text = await DownloadTextAsync(blockBlob);
这段代码是否正确并且确实是完全异步的?你会以不同的方式实现吗?
我希望得到一些额外的说明:
GetContainerReference和GetBlockBlobReference不需要异步,因为它们还没有联系服务器,对吧?streamReader.ReadToEnd是否需要异步?我对@987654327@ 做了什么有点困惑。在调用
EndDownloadToStream时,我的内存流中是否包含所有 数据?还是流只打开预读?
更新:(自 Storage 2.1.0.0 RC 起)
现在原生支持异步。
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageAccountConnectionString"));
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference("container1");
CloudBlockBlob blockBlob = container.GetBlockBlobReference("blob1.txt");
string text = await blockBlob.DownloadTextAsync();
【问题讨论】:
标签: c# azure .net-4.5 async-await azure-blob-storage