Cancel an 'HttpClient' POST request

 ̄綄美尐妖づ 提交于 2019-12-06 07:40:39

问题


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?


回答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
  }



回答2:


Cancelling a task doesn't terminate it instantly. You have to check manually before doing your work by checking the token's status:

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

// Post request here...

This article is quite useful: How to: Cancel a Task and Its Children



来源:https://stackoverflow.com/questions/31471291/cancel-an-httpclient-post-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!