Using Threads to Call an API Multiple Times in a Loop in C#

I am facing a challenge with my project. I need to invoke an API several times within a loop and collect the responses into a List. After gathering the responses, I plan to execute some operations on that List. Currently, I am calling the API sequentially, which means each call waits for the response before proceeding to the next. My goal is to perform these API calls using threads, so I can collect all the responses at once and then apply my business logic on the results.

Here is a sample of my code:

                    foreach (var item in collection)
                    {
                       // intending to initiate a thread here
                       resultList.Add(MakeApiCall(parameters));
                    }
                // need to ensure all threads complete before continuing.
                   ApplyBusinessRules(resultList);

hey, you might try using async/await which is simpler & can help with handling concurrent tasks in C#. Tasks await responses w/o blocking the main thread. The “.WhenAll()” method can be helpful to wait for all tasks to finish before proceeding. gives you a non-blocking n efficient way!

yo, another way to do it is by leveraging Task.Run(). It spwans a new task for each API call, adn you can await each task to finish. It’s kind of a blend of threads but simpler with the task library. works charm if async/await ain’t your play.