I am uploading an image with HttpClient.PostAsync()
on my Windows Phone 8 app. The user has the option to cancel this upload via a UI button.
To cancel the POST request, I set a CancellationToken
. But this doesn't work. After the cancellation request, I see still see the upload taking place in my proxy and it is evident that the request was ignored. My code:
using (var content = new MultipartFormDataContent())
{
var file = new StreamContent(stream);
file .Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
FileName = "filename.jpg",
};
file.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
content.Add(file);
await httpclient.PostAsync(new Uri("myurl", UriKind.Absolute), content,
cancellationToken);
}
Please also note that I have a CancellationTokenSource
for the CancellationToken
. After the user clicks on the Cancel button, tokensource.Cancel()
is called. Also, the images in my testcase are from 1 to 2 MB (not that big).
So, is there a way to cancel an HttpClient
POST request?
try
{
var client = new HttpClient();
var cts = new CancellationTokenSource();
cts.CancelAfter(3000); // 3 seconds
var request = new HttpRequestMessage();
await client.PostAsync(url, content, cts.Token);
}
catch(OperationCanceledException ex)
{
// timeout has been hit
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With