How to cancel a HttpClient GET web request

Can I cancel the HttpClient GET web request in Windows 8. I'm looking for a solution to cancel my web request if the user presses a key from the page. In my application, I am using a static class to create a web request.

Alos, I use MVVM Light and static viewmodels inside the application.

In the current situation, even if the user presses the "Back" button, vm will remain alive, and the callback will reach and be executed in vm .

So, I'm looking for a solution to cancel the request in the back press.

+7
windows-8 windows-runtime
source share
1 answer

try it

 protected async override void OnNavigatedTo(NavigationEventArgs e) { await HttpGetRequest(); } public CancellationTokenSource cts = new CancellationTokenSource(); private async Task HttpGetRequest() { try { DateTime now = DateTime.Now; var httpClient = new HttpClient(); var message = new HttpRequestMessage(HttpMethod.Get, "https://itunes.apple.com/us/rss/toppaidapplications/limit=400/genre=6000/json"); var response = await httpClient.SendAsync(message, cts.Token); System.Diagnostics.Debug.WriteLine("HTTP Get request completed. Time taken : " + (DateTime.Now - now).TotalSeconds + " seconds."); } catch (TaskCanceledException) { System.Diagnostics.Debug.WriteLine("HTTP Get request canceled."); } } private void btnCancel_Click(object sender, RoutedEventArgs e) { cts.Cancel(); } 
+5
source

All Articles