取消' HttpClient' POST请求

时间:2015-07-17 08:20:39

标签: c# windows-phone-8 http-post httpclient cancellation

我正在使用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);
}

另请注意,我CancellationTokenSource有一个CancellationToken。用户单击“取消”按钮后,将调用tokensource.Cancel()。此外,我的测试用例中的图像是1到2 MB(不是那么大)。

那么,有没有办法取消HttpClient POST请求?

2 个答案:

答案 0 :(得分:1)

   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
  }

答案 1 :(得分:0)

取消任务不会立即终止。在完成工作之前,您必须通过检查令牌的状态来手动检查:

if (ct.IsCancellationRequested) 
{
    ct.ThrowIfCancellationRequested();
}

// Post request here...

这篇文章非常有用:How to: Cancel a Task and Its Children