1

I am looking to make a different thread for different api calls, because of the runtime. I do not know much about threads, so feel free so correct me if this is the wrong way to go, it was just suggested to me by someone. Any help would be appreciated. And for each api call I set that API to a variable, meaning, in each thread I would need access to that variable as well as creating a new thread at the same time. Again, I am inexperienced, so cut me some slack please.

I know hwo to create threads, but i am not sure how to implement this into what I need based on the google searches I have done

[HttpPost("/{upperInt}/{lowerInt}")]
        public async Task<IActionResult> PostRequest(int upperInt, int lowerInt)
        {
            Console.WriteLine("here");
            static async Task<YahooModel> grabData(String s)
            {
                using (var client = new HttpClient())
                {
                    Console.WriteLine("starting" + s);
                    String url = "https://financialmodelingprep.com/api/v3/historical-price-full/" + s.ToUpper() + "?{my api key goes here}";
                    var response = await client.GetStringAsync(url);
                    YahooModel returnObj = JsonConvert.DeserializeObject<YahooModel>(response);
                    Console.WriteLine("ending" + s);
                    return returnObj;
                }
            }
            YahooModel IVE = await grabData("ive");
            YahooModel IVV = await grabData("ivv");
            YahooModel IVW = await grabData("ivw");
            YahooModel IJJ = await grabData("ijj");
            YahooModel IJH = await grabData("ijh");
            YahooModel IJK = await grabData("ijk");
            YahooModel IWN = await grabData("iwn");
            YahooModel IWM = await grabData("iwm");
            YahooModel IWO = await grabData("iwo");




            return View("Index");
        }
Speurox
  • 25
  • 5

1 Answers1

1

You don't need to create Threads manually in this case, just use Task.WhenAll to wait for all created tasks (removing await before grabData):

var IVETask = grabData("ive");
var IVVTask = grabData("ivv");
var IVWTask = grabData("ivw");
....
await Task.WhenAll(IVETask, IVVTask, IVWTask,....);
YahooModel IVE = IVETask.Result;
.....
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • Thank you!!! But how exactly is this making it faster? They are all still getting created seperately are they not? Isn't this just waiting for them all to be created first? – Speurox Jun 12 '20 at 22:56
  • 1
    @Speurox your `grabData` returns already started `Task` if you `await` it your method will stop until this `Task` finishes, with this code you will start all `Task`s and then wait all of them. There are multiple sources explaining this in more detail, you can start reading from [this](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/) for example. – Guru Stron Jun 12 '20 at 23:03