Flawinne Julien
Flawinne Julien

Reputation: 33

Does it going to be asynchronous

I currently have a question about async/await in REST api with dotnet core. I m working on an api that needs to make some http call with the GetAsync method from HttpClient. Here is how it works :

This my get method into my controller :

[HttpGet]
    public async Task<IActionResult> Get(string url, string aid)
    {
        try
        {
            //...

            var cancellationTokenSource = new CancellationTokenSource();
            var task = Task.Factory.StartNew(async () => await _htmlService.HtmlLinkCheck(aid, cancellationTokenSource.Token, correctUrl), cancellationTokenSource.Token);
            ConnectionsHelper.RegisterTask(aid, task, cancellationTokenSource);
            ConnectionsHelper.UpRequest(aid);

            return Ok("Ok");
        }
        catch (Exception exception)
        {
            return this.InternalServerError(exception);
        }
    }

this method is calling a service which is injected and configured in the startup file like this :

services.AddScoped<IRequestService, RequestService>();
        services.AddScoped<IHtmlCheckService, HtmlCheckService>();

into that HtmlCheckService into the HtmlLinkCheck i'm calling the requestService to make the call :

private async Task CheckHtmlLink(CancellationToken token)
    {
            //...

            var result = await _requestService.GetRequest(handledUrl.url);

and the GetRequest method do :

public async Task<string> GetRequest(Uri url)
    {
        // ...

            var response = await _httpClient.GetAsync(url);

_httpClient is a static variable (used by all the different instance of RequestService) :

private static HttpClient _httpClient;

    public RequestService()
    {
        var handler = new HttpClientHandler();
        if (handler.SupportsAutomaticDecompression)
        {
            handler.AutomaticDecompression = DecompressionMethods.GZip |
                                             DecompressionMethods.Deflate;
        }

        _httpClient = new HttpClient(handler);

        _httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0");

    }

If my i m make let s say 100 requests to my REST API, does for each request the calls to GetAsync are going to be thread safe (not one call at a time, but calls in parallel ) between each request (instances of RequestService because of AddScope method to create the injection) ? It looks like if it works in parallel but how can i be sure of it ?

Would it be more effective to create a new instance of httpClient per instance of RequestService ?

Thanks in advance for your answers

Upvotes: 0

Views: 71

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 456537

HttpClient is designed to allow multiple simultaneous requests.

It does not allow you to change properties like BaseAddress or DefaultRequestHeaders once it has been used; if you need different properties set for different requests, then you should use a different HttpClient instance for those requests.

But in the general case, yes, you should use one HttpClient instance for every request that shares its property values.

Upvotes: 2

Related Questions