Skip to content

How to use CancellationToken with HttpClient #106558

Description

@MhdTlb

I'm trying to setup a timeout for each separate HttpClient.Send call in .net8.0.

So I used CancellationTokenSource but It seems that it starts the timer as soon as I create it instead of starting the timer when calling HttpClient Send method.
Here is my unit tests result:

[TestMethod]
[DataRow(1)]
[DataRow(10)]
[DataRow(100)]
[DataRow(1000)]
[DataRow(10000)]
[DataRow(100000)]
[DataRow(1000000)]
public void HttpClient_Send_CancellationTokenSource(int timeout)
{
    var httpClient = new HttpClient();
    var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(timeout));

    var request = new HttpRequestMessage(HttpMethod.Get, "https://google.com");
    Thread.Sleep(2 * timeout);
    var response = httpClient.Send(request, cancellationToken: cts.Token);
}

So all unit tests failed with this exception: System.Threading.Tasks.TaskCanceledException: The operation was canceled. ---> System.OperationCanceledException: The operation was canceled.

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-System.Net.Httpneeds-author-actionAn issue or pull request that requires more info or actions from the author.questionAnswer questions and provide assistance, not an issue with source code or documentation.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions