Joe*_*ehl 5 c# httpclient http-post cancellation windows-phone-8
我正在使用HttpClient.PostAsync()我的 Windows Phone 8 应用上传图像。用户可以选择通过 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);
}
Run Code Online (Sandbox Code Playgroud)
另请注意,我有一CancellationTokenSource对CancellationToken。在用户点击取消按钮后,tokensource.Cancel()被调用。此外,我的测试用例中的图像从 1 到 2 MB(不是那么大)。
那么,有没有办法取消HttpClientPOST 请求?
取消任务并不会立即终止它。在开始工作之前,您必须通过检查令牌的状态来手动检查:
if (ct.IsCancellationRequested)
{
ct.ThrowIfCancellationRequested();
}
// Post request here...
Run Code Online (Sandbox Code Playgroud)
这篇文章非常有用:如何:取消任务及其子任务
| 归档时间: |
|
| 查看次数: |
5282 次 |
| 最近记录: |