Reputation: 7709
I need to add the possibility of canceling an http request in an old c# project.
The project uses HttpClient::GetStreamAsync which does not seem to support Cancellation tokens.
Can a GetStreamAsync call be canceled? What other possibilities do I have?
Upvotes: 9
Views: 2862
Reputation: 3526
2022 Update: I have left the link to the MSDN article because at the moment I write this the link still works. However, the link is older and may eventually cease to work, and I noticed the code formatting I saw back in 2017 is no longer there today. Additionally, based on comments below my answer, I have lightly edited the content of my answer to remove an unhelpful sentence as well as a pointlessly italicized word.
Original Answer: 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.
Upvotes: 7
Reputation: 2474
Same as Johns answer, just as an extension method:
internal static class HttpClientExtensions
{
public async static Task<Stream> GetStreamAsync(this HttpClient httpClient, string url, CancellationToken ct)
{
var response = await httpClient.GetAsync(new Uri(url), ct);
return await response.Content.ReadAsStreamAsync();
}
}
Upvotes: 0
Reputation: 11417
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();
}
}
Upvotes: 6