cancel a c# httpClient GetStreamAsync call

Because of how a stream works, it cannot be canceled. I spotted an alternative solution from a MSDN blog post written in 2012. It might be of some help to you. The author is using GetStringAsync but the principle also applies to GetStreamAsync. Article: Await HttpClient.GetStringAsync() and cancellation.

In the MSDN article the author is using GetAsync(...) which can take a cancellation parameter. A simple solution for Nathan's issue could be something like this...

CancellationTokenSource cancellationSource = new CancellationTokenSource();
CancellationToken cancellationToken = cancellationSource.Token;

Uri uri = new Uri('some valid web address'); 
HttpClient client = new HttpClient();
await client.GetAsync(uri, cancellationToken);

// In another thread, you can request a cancellation.
cancellationSource.Cancel();

Note that the cancellation is made on the CancellationTokenSource object, not the CancellationToken object.


Here is a simple example.

public async Task<Stream> GetWebData(string url, CancellationToken? c = null)
{
    using (var httpClient = new HttpClient())
    {
        var t = httpClient.GetAsync(new Uri(url), c ?? CancellationToken.None);
        var r = await t;
        return await r.Content.ReadAsStreamAsync();
    }
}

Tags:

C#

Httpclient