How to cancel HttpClient GET Web request
Asked Answered
O

2

8

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.

Odds answered 2/8, 2013 at 9:45 Comment(2)
You can use CancellationToken for cancelling async methods. It's a way of doing it, might be others.Estep
Can you please add the way of cancel the request with CancelationToken, as answer. Then i will mark it as answerOdds
T
11

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();
}
Tocology answered 2/8, 2013 at 11:20 Comment(3)
Please note, that for Windows 8.1 runtime things have changed "just a little" bit - http client cancel request in windows 8.1, so the currect answer is accurate only for runtime in windows 8.0.Aprilette
OP has also asked for W8 only. See the tags of question.Tocology
I've seen tags for sure and your answer is perfectly fine for Windows 8. Just added comment for those, who like me may look the similar info for latest (so far) Windows and point them to the appropriate place.Aprilette
O
1

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.

Oder answered 26/5, 2022 at 3:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.