[c#] 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();
}

This question is related to c# task-parallel-library dotnet-httpclient

The answer is


Promoting @JobaDiniz's comment to an answer:

Do not do the obvious thing and dispose the HttpClient instance, even though the code "looks right":

async Task<HttpResponseMessage> Method() {
  using (var client = new HttpClient())
    return client.GetAsync(request);
}

The same happens with C#'s new RIAA syntax; slightly less obvious:

async Task<HttpResponseMessage> Method() {
  using var client = new HttpClient();
  return client.GetAsync(request);
}

Instead, cache a static instance of HttpClient for your app or library, and reuse it:

static HttpClient client = new HttpClient();

async Task<HttpResponseMessage> Method() {
  return client.GetAsync(request);
}

(The Async() request methods are all thread safe.)


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.


Another reason can be that if you are running the service (API) and put a breakpoint in the service (and your code is stuck at some breakpoint (e.g Visual Studio solution is showing Debugging instead of Running)). and then hitting the API from the client code. So if the service code a paused on some breakpoint, you just hit F5 in VS.


I was using a simple call instead of async. As soon I added await and made method async it started working fine.

public async Task<T> ExecuteScalarAsync<T>(string query, object parameter = null, CommandType commandType = CommandType.Text) where T : IConvertible
        {
            using (IDbConnection db = new SqlConnection(_con))
            {
                return await db.ExecuteScalarAsync<T>(query, parameter, null, null, commandType);
            }
        }

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.

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


In my situation, the controller method was not made as async and the method called inside the controller method was async.

So I guess its important to use async/await all the way to top level to avoid issues like these.


Another possibility is that the result is not awaited on the client side. This can happen if any one method on the call stack does not use the await keyword to wait for the call to be completed.


in my .net core 3.1 applications I am getting two problem where inner cause was timeout exception. 1, one is i am getting aggregate exception and in it's inner exception was timeout exception 2, other case was Task canceled exception

My solution is

catch (Exception ex)
            {
                if (ex.InnerException is TimeoutException)
                {
                    ex = ex.InnerException;
                }
                else if (ex is TaskCanceledException)
                {
                    if ((ex as TaskCanceledException).CancellationToken == null || (ex as TaskCanceledException).CancellationToken.IsCancellationRequested == false)
                    {
                        ex = new TimeoutException("Timeout occurred");
                    }
                }                
                Logger.Fatal(string.Format("Exception at calling {0} :{1}", url, ex.Message), ex);
            }

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to task-parallel-library

What is the difference between Task.Run() and Task.Factory.StartNew() Task.Run with Parameter(s)? HttpClient - A task was cancelled? Running multiple async tasks and waiting for them all to complete Deserialize JSON to Array or List with HTTPClient .ReadAsAsync using .NET 4.0 Task pattern Calling async method synchronously How can I tell Moq to return a Task? When to use Task.Delay, when to use Thread.Sleep? Awaiting multiple Tasks with different results How to safely call an async method in C# without await

Examples related to dotnet-httpclient

How do I pass an object to HttpClient.PostAsync and serialize as a JSON body? Custom header to HttpClient request Adding headers when using httpClient.GetAsync HttpClient - A task was cancelled? How to get content body from a httpclient call? Pass multiple complex objects to a post/put Web API method Deserialize JSON to Array or List with HTTPClient .ReadAsAsync using .NET 4.0 Task pattern Why is HttpClient BaseAddress not working? Make Https call using HttpClient Deciding between HttpClient and WebClient