Nitha Paul
Nitha Paul

Reputation: 1401

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.

Upvotes: 8

Views: 10883

Answers (2)

j4jada
j4jada

Reputation: 722

The answer by @Farhan Ghumra is correct. Since we have moved to .Net 6 just like to add the following to the answer.

After you’re completely done with the CancellationTokenSource, dispose it directly E.g use cts.Dispose() (because you’ll most likely be using this with UI code and needing to share it with click event handling code, which means you wouldn’t be able to dispose of it with a using block)

More information can be found here.

Upvotes: 1

Farhan Ghumra
Farhan Ghumra

Reputation: 15296

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

Upvotes: 11

Related Questions