Home > Software design >  Is this going to create multiple threads?
Is this going to create multiple threads?

Time:09-28

I have the following method which is returning me a list of stock prices.

var tickers = Ticker.text.splice(',',' ');
var service = new StockService();
var tickerLoadingTasks = new List<Task<IEnumerable<StockePrice>>>();
foreach(var ticker in tickers)
{
   var loadTask = service.GetStockPriceFor(ticker,cancellationTokenSource.Token)
   tickerLoadingTasks.Add(loadTask);
}

await Task.WhenAll(tickerLoadingTasks);
// code for updating UI

I have above method which returns me list of stock price data. My confusion is that for each value in tickers, is new thread created or what?

GetStockPrice returns me Task of List of the stock prices for each stock.

CodePudding user response:

Assuming that StockService is an Http client, GetStockPriceFor will do an HTTP request. If the code is implemented correctly, the returned Task can be awaited to get the result of the HTTP call. While awaiting the Task, no thread is used.

The idea of async/await and I/O calls is that you can continue using the thread for something else while the operating system waits for the I/O call to finish. Once it's finished, a thread will be used to process the result of the I/O call.

Now remember, this is based upon the assumption you're doing an HTTP call.

This is a huge if since you don't show the actual implementation of the code. It could be that the code fetches the results synchronously and uses Task.FromResult to give you a Task that will immediately complete and not even switch threads.

  • Related