-1

I am developing an API, in this API I have a service with a method and this method has to call three methods in different repositories. Each of this methods have a Https request, the call has a respond and I want to get the information from this respond.

Now, we are waiting for each of this calls and the performance is awful.

How can I do these three call to the same time? I know using parallel but I don't know how.

Service:

    public async Task<object> GetTenantSettings(string source, string tenantId)
    {
        var tenantSettings = await _repository1.GetTenant(tenantId);
        var accountCount = await _repository2.GetAccount(tenantId);
        var userCount = await _repository3.GetUsers(source, int.Parse(tenantId));

        var TenantSettingsModel = MapTenant(accountCount, userCount, tenantSettings); // To map, out of scope of the problem

        return TenantSettingsModel;
    }

The interface of the repository, I show one but all have the same idea.

    Task<int> GetAccount(string tenantId);

Now we are calling one method and after the others, how can I call it to the same time and get the information?

Liam
  • 27,717
  • 28
  • 128
  • 190
CMorillo
  • 191
  • 1
  • 10
  • Do you want parallel or asynchronous (not the same thing)? – Liam Jun 19 '19 at 12:07
  • instead of awaiting them one by one use get all the tasks in a variable and use the static method Task.WhenAll(params Task[] tasks) to perfrom everything in parallel. – Brezelmann Jun 19 '19 at 12:09

1 Answers1

3

I'm presuming you want a none blocking async result, not actual parallel, in that case it's as easy as adding a Task.WhenAll:

var tenantSettings = _repository1.GetTenant(tenantId);
var accountCount = _repository2.GetAccount(tenantId);
var userCount =  _repository3.GetUsers(source, int.Parse(tenantId));

await Task.WhenAll(tenantSettings, accountCount, userCount);

var TenantSettingsModel = MapTenant(accountCount.Result, userCount.Result, tenantSettings.Result);

Actual parallel processing would require spawning new threads using Task.Run(). This is possible but presuming your calls to repository are IO bound, not CPU bound, your unlikely to gain much benefit, where-as this approach should maximise your IO usage without blocking the thread.

Remember, "Faster" is not as simple as it sounds. If this is a multi threaded environment (like for example a web application) then you could rob peter to pay paul (particularly when spawning new threads). The only way to actual confirm if something is "faster" is to benchmark it under load.

Liam
  • 27,717
  • 28
  • 128
  • 190