http client cancel request in windows 8.1

那年仲夏 提交于 2019-12-03 07:50:56

问题


I am working on a Windows Phone 8.1 project. There are two versions of http client in Windows 8.1 - system.net.http and windows.web.http. Microsoft recommends using the later.

So, I decided to go with it. But I can't find a way to cancel the web request started with windows.web.http.httpclient. In system.net.http.httpclient there is a CancelPendingRequests method but no similar methods exist for the later option.

So, is it possible to cancel the web request and if so how?

Sample Code:

Consider a Http Get request google as follows. I would like to cancel it before its completion if the user wishes so.

// Windows Phone 8.1 project (not silverlight)
public sealed partial class MainPage : Page
{
    Windows.Web.Http.HttpClient client = new Windows.Web.Http.HttpClient();

    public MainPage()
    {
        this.InitializeComponent();

        this.NavigationCacheMode = NavigationCacheMode.Required;

        Windows.Phone.UI.Input.HardwareButtons.BackPressed += (s, e) =>
        {
           CancelGet();
        }
    }

    private void CancelGet()
    {
       // What to put here??
       // tried client.Dispose();
       // but still get request completes successfully
    }

    private async void Button_Click(object sender, RoutedEventArgs e)
    {
        string res = await client.GetStringAsync(new Uri("http://www.google.com", UriKind.Absolute));

        System.Diagnostics.Debug.WriteLine("result obtained\n" + res);
    }
 }

None of the methods of HttpClient support CancellationToken.

Also I tried to call Dispose() on the HttpClient while the request is ongoing (say GetStringAsync). However still neither any exception is thrown nor the request is cancelled; the GetStringAsync completes as normal and shows the correct result.


回答1:


Haven't tested it yet, but this could work:

await client.GetStringAsync(new Uri("http://www.google.com")).AsTask(cancellationToken);

If you don't have the need for cancellation tokens, you can also cancel the IAsyncOperation directly like this:

var operation = _httpClient.GetStringAsync(new Uri("http://www.google.com"));
var response = await operation;

operation.Cancel();

This blog post is a good read on the whole Task vs IAsyncOperation topic.



来源:https://stackoverflow.com/questions/23457797/http-client-cancel-request-in-windows-8-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!