HttpClient.GetAsync( ) & CloudBlobBlock.UploadFromStreamAsync( ) - 这是如何执行的?

HttpClient.GetAsync( ) & CloudBlobBlock.UploadFromStreamAsync( ) - how is this executed?

我需要从一个地方下载一个文件,然后将其上传到 azure blob。完成后,我还需要 return blob 的大小:

public async Task<Stream> Download(string url)
{
   using (var client = new HttpClient())
   {
        return await client.GetStreamAsync(url);
   }
}

public async Task<long> Upload(Stream stream, string filename) 
{
   var container = GetBlobContainer(..);
   var blob = container.GetBlockBlobReference(filename);

   await blob.UploadFromStreamAsync(stream);
   blob.FetchAttributes();

   return blob.Properties.Length;
}

public async Task<long> Action()
{
   var stream = await Download("https://.....");
   var size = await Upload(stream, "newfile.dat");

   return size;
}

问题

奖金:

Will the Upload method be called before the complete stream is downloaded into memory?

不,所以默认情况下 HttpClient 会将整个响应下载到内存中,然后 然后 给你流。参见:HttpClient.SendAsync. The overload you're using specifies the HttpCompletionOption.ResponseContentRead。但更糟糕的是,您的代码将无法运行,您在使用流之前处理了 HttpClient,这会导致流被关闭。

Will Upload start uploading bytes to azure as soon as the HttpClient starts to receive bytes?

再说一次,不,请参阅之前的回答。

If not - is it possible to make it do so?

是的,使用我之前列出的 SendAsync 重载并设置适当的 HttpCompletionOption,哦,并解决我提到的处理问题。 :)

How many different contexts will be generated? Should .ConfigureAwait(false) be used to limit context switches?

不确定 "conetxts" 是什么意思,我假设执行上下文?如果没有看到更多您的代码,这很难说。但我建议使用 .ConfigureAwait(false) 除非有一些 UI 涉及。

Is blob.FetchAttributes() the right way of getting the size of the blob?

就个人而言,我会自己使用客户响应 headers 中的内容长度。但根据 MSDN 文档,这看起来是正确的。