.NET 4.5 async & await を使用して、完全に非同期の 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
非同期である必要がありますか?私は何をしているのか少し混乱して
BeginDownloadToStream
います..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();