My requirement is quite weird.
I have SomeMethod() which calls GetDataFor().
public void SomeMethod()
{
for(int i = 0
There's a couple of different approaches.
First, you could keep it synchronous and just execute them in parallel (on different threads). Parallel LINQ is better than Parallel if you want to collect all the results in the calling method before continuing:
public data[] SomeMethod()
{
return Enumerable.Range(0, 100)
.AsParallel().AsOrdered()
.Select(GetDataFor).ToArray();
}
Second, you could make it asynchronous. To make something truly asynchronous, you need to start at the lowest level (in this case, "call a remote API" and "store to database") and make that asynchronous first. Then you can make GetDataFor asynchronous:
public async Task GetDataForAsync(int i)
{
await .. //call a remote API asynchronously
await .. //store to database asynchronously
return data;
}
Then you can make SomeMethod asynchronous as well:
public Task SomeMethodAsync()
{
return Task.WhenAll(
Enumerable.Range(0, 100).Select(GetDataForAsync)
);
}
Making the code asynchronous is more work - more of the code has to change - but it's better in terms of scalability and resource use.