HttpClient - was the task canceled?

It works great when one or two tasks have an error "The task was canceled" when we have more than one task.

enter image description here

List<Task> allTasks = new List<Task>(); allTasks.Add(....); allTasks.Add(....); Task.WaitAll(allTasks.ToArray(), configuration.CancellationToken); private static Task<T> HttpClientSendAsync<T>(string url, object data, HttpMethod method, string contentType, CancellationToken token) { HttpRequestMessage httpRequestMessage = new HttpRequestMessage(method, url); HttpClient httpClient = new HttpClient(); httpClient.Timeout = new TimeSpan(Constants.TimeOut); if (data != null) { byte[] byteArray = Encoding.ASCII.GetBytes(Helper.ToJSON(data)); MemoryStream memoryStream = new MemoryStream(byteArray); httpRequestMessage.Content = new StringContent(new StreamReader(memoryStream).ReadToEnd(), Encoding.UTF8, contentType); } return httpClient.SendAsync(httpRequestMessage).ContinueWith(task => { var response = task.Result; return response.Content.ReadAsStringAsync().ContinueWith(stringTask => { var json = stringTask.Result; return Helper.FromJSON<T>(json); }); }).Unwrap(); } 
+165
c # task-parallel-library
Mar 21 '15 at 6:15
source share
3 answers

There are 2 possible reasons for which:

  • Something called Cancel() on the CancellationTokenSource associated with the cancellation token until the task completes.
  • The request timed out, that is, it was not completed within the time specified by you in HttpClient.Timeout .

My guess is a timeout. (If it was an explicit revocation, you would probably understand this.) You can be more confident by checking the exception:

 try { var response = task.Result; } catch (TaskCanceledException ex) { // Check ex.CancellationToken.IsCancellationRequested here. // If false, it pretty safe to assume it was a timeout. } 
+237
Mar 23 '15 at 15:33
source

I ran into this problem because my Main() method did not wait for the task to complete before returning, therefore the Task<HttpResponseMessage> myTask is canceled when my console program is completed.

The solution was to call myTask.GetAwaiter().GetResult() in Main() (from this answer ).

+16
Sep 10 '17 at 2:41 on
source

Another possibility is that the result is not expected on the client side. This can happen if any one method in the call stack does not use the wait keyword to wait for the call to complete.

+9
Sep 10 '17 at 15:15
source



All Articles