Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cancel a c# httpClient GetStreamAsync call

Tags:

c#

httpclient

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?

like image 913
Nathan Avatar asked Dec 18 '16 14:12

Nathan


People also ask

Can I cancel AC ticket?

If a confirmed ticket is cancelled more than 48 hrs before the scheduled departure of the train, flat cancellation charges shall be deducted @ Rs.240/- for AC First Class/Executive Class, Rs.200/- for AC 2 Tier/First Class, Rs. 180 for AC 3 Tier/AC Chair car/ AC 3 Economy, Rs.120/- for Sleeper Class and Rs.60/- for ...

Can we cancel AC train ticket online?

The cancellation can only be done online. If an e-ticket is cancelled within 48 hours and up to 12 hours prior to the scheduled departure of the train , the Indian Railways deducts 25% of the base fare + GST applicable for all AC classes.

Can I cancel my train ticket before 2 hours?

(iii) For cancellation of confirmed tickets less than 6 hrs be- fore the scheduled departure of the train and upto 2 hrs of the actual departure of the train, the cancellation charges will be 50% of the fare paid by you, subject to flat cancellation charges for each class.


1 Answers

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.

like image 193
kevin628 Avatar answered Sep 18 '22 22:09

kevin628