1

Problem Statement

I need to send multiple API calls at one shot.

I have three different API endpoints as shown below, and all these need to be called together almost as quickly as possible. It's all independent of each other.

public async Task<string> GetA(string a)
{
}

public async Task<string> GetB(int a)
{
}

public async Task<string> GetC(int a, string a)
{
}

What I tried

I was trying like this:

public async Task CallMultipleAPIs()
{
    await GetA("");
    await GetB(1);
    await GetC(1, "");
}

How to implement parallelism here?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
KBNanda
  • 595
  • 1
  • 8
  • 25

1 Answers1

6

What you need is concurrency (not parallelism - i.e., multiple threads).

Concurrent asynchronous code is done by using Task.WhenAll:

public async Task CallMultipleAPIs()
{
  var taskA = GetA("");
  var taskB = GetB(1);
  var taskC = GetC(1, "");
  await Task.WhenAll(taskA, taskB, taskC);
}
Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
  • 2
    To clarify: As soon as `GetA()` makes an I/O request (like a network request) control passes back to `CallMultipleAPIs()` and then `GetB()` is called, etc. This is "concurrent" in that all of this happens on the same thread. It is not "parallel", since "parallel" means running code on different threads. – Gabriel Luci Jan 16 '22 at 04:47