Cancel cClick httpClient call GetStreamAsync

I need to add the ability to cancel the http request in an old C # project.

The project uses HttpClient :: GetStreamAsync, which does not seem to support cancellation tokens.

Can I cancel a call to GetStreamAsync? What other opportunities do I have?

+5
source share
2 answers

Due to how the stream works, it cannot be undone. I found an alternative solution in an MSDN blog post written in 2012. Perhaps it will help you. The author uses GetStringAsyncbut this principle also applies to GetStreamAsync. Article: Wait for HttpClient.GetStringAsync () and cancel .

MSDN GetAsync(...) . ...

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();

, CancellationTokenSource, CancellationToken.

+5

.

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();
    }
}
0

Source: https://habr.com/ru/post/1664093/


All Articles