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.
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