Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel HttpClient GET Web request

Is it possible to cancel HttpClient GET web request in Windows 8. I am looking for a solution to cancel my web request if the user press back key from the page. In my app i am using a static class for creating web request.

Alos i am using MVVM Light, and static viewmodels inside the app.

In the current situation, even if the user press the back button, the vm stay alive and the call back reaches and executes in the VM.

So i am looking for a solution to cancel the request on back press.

like image 308
Nitha Paul Avatar asked Aug 02 '13 09:08

Nitha Paul


1 Answers

Try this

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();
}
like image 173
Farhan Ghumra Avatar answered Sep 28 '22 01:09

Farhan Ghumra