我正在使用HttpClient.PostAsync()在我的Windows phone8应用上载图像。用户可以选择通过UI按钮取消此上传。
要取消POST请求,我设置了一个CancellationToken。但这不管用。在取消请求之后,我仍然看到上传发生在我的代理中,很明显,该请求被忽略了。我的代码:
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);
}还请注意,我有一个用于CancellationToken的CancellationTokenSource。用户单击Cancel按钮后,将调用tokensource.Cancel()。此外,我测试用例中的图像大小为1到2MB(不是那么大)。
那么,有没有办法取消HttpClient POST请求呢?
发布于 2017-11-20 21:43:08
try
{
var client = new HttpClient();
var cts = new CancellationTokenSource();
cts.CancelAfter(3000); // 3seconds
var request = new HttpRequestMessage();
await client.PostAsync(url, content, cts.Token);
}
catch(OperationCanceledException ex)
{
// timeout has been hit
}发布于 2015-07-17 21:27:12
取消任务并不会立即终止它。在执行工作之前,您必须通过检查令牌的状态进行手动检查:
if (ct.IsCancellationRequested)
{
ct.ThrowIfCancellationRequested();
}
// Post request here...https://stackoverflow.com/questions/31471291
复制相似问题