I got a weird situation when using C# HttpClient
. I am trying to use the HttpCompletionOption.ResponseHeadersRead
option in GetAsync
to get response headers without content as quickly as possible. But when downloading files, I am in await GetAsync
until the whole content is downloaded over the network (i checked this with Fiddler). I am attaching an example code that downloads a 1Gb test file. The example application will hang in the await client.GetAsync
until all file content is received over the network. How do I get control back when the headers have finished receiving and not wait for the complete content transfer over the network?
using System;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
public class Program
{
private const int HttpBufferSize = 81920;
private static async Task Main(string[] args)
{
var url = new Uri("http://212.183.159.230/1GB.zip");
await DownloadFileAsync(@"C:\1GB.zip", url, CancellationToken.None).ConfigureAwait(false);
}
private static async Task DownloadFileAsync(string filePath, Uri fileEndpoint,
CancellationToken token)
{
using var client = new HttpClient();
using var response = await client.GetAsync(fileEndpoint, HttpCompletionOption.ResponseHeadersRead, token).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
await using var contentStream = await response.Content.ReadAsStreamAsync(token).ConfigureAwait(false);
await using var stream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None);
await contentStream.CopyToAsync(stream, HttpBufferSize, token).ConfigureAwait(false);
}
}