HttpClient - A task was cancelled?

It works fine when have one or two tasks however throws an error "A task was cancelled" when we have more than one task listed.

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();
}

There's 2 likely reasons that a TaskCanceledException would be thrown:

  1. Something called Cancel() on the CancellationTokenSource associated with the cancellation token before the task completed.
  2. The request timed out, i.e. didn't complete within the timespan you specified on HttpClient.Timeout.

My guess is it was a timeout. (If it was an explicit cancellation, you probably would have figured that out.) You can be more certain by inspecting the exception:

try
{
    var response = task.Result;
}
catch (TaskCanceledException ex)
{
    // Check ex.CancellationToken.IsCancellationRequested here.
    // If false, it's pretty safe to assume it was a timeout.
}

I ran into this issue because my Main() method wasn't waiting for the task to complete before returning, so the Task<HttpResponseMessage> myTask was being cancelled when my console program exited.

C# ≥ 7.1

You can make the main method asynchronous and await the task.

public static async Task Main(){
    Task<HttpResponseMessage> myTask = sendRequest(); // however you create the Task
    HttpResponseMessage response = await myTask;
    // process the response
}

C# < 7.1

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


var clientHttp = new HttpClient();
clientHttp.Timeout = TimeSpan.FromMinutes(30);

The above is the best approach for waiting on a large request. You are confused about 30 minutes; it's random time and you can give any time that you want.

In other words, request will not wait for 30 minutes if they get results before 30 minutes. 30 min means request processing time is 30 min. When we occurred error "Task was cancelled", or large data request requirements.