re: If async & awaits is used with Task in ASP.NET (C#), is there a need to manually create threads? VIEW POST

TOP OF THREAD FULL DISCUSSION
re: First of all, thank you for your explanation. In ASP.NET documentation, I read that asynchronous methods use threads from existing thread group of ...
 

Unless you are having ASP.NET requests blocked and users feel lag, you don't need to create different thread pool. Instead of threads, you can create a new thread pool and assign tasks to the new thread pool but you will end up doing unnecessary synchronization and scheduling issues. Tasks are very well optimized to give great performance, you will not achieve it in threads without doing same things which Tasks are already doing.

I would suggest that you profile your code, find out which methods are actually blocking server. You should consider some optimizations such as reusing Tasks, not using tasks for very small operation and reuse Task object and use Task.WhenAll

Example,


   // this is wrong...

   public async Task<List<string>> GetResults() {

      List<string> results = new List<string>();

      for(var site in sites) {
         results.Add( await GetSiteResultAsync(site)); 
      }
      return results;
   }

   // this is correct ...

   public Task<string[]> GetResults() {

      List<Task<string>> results = new List<Task<string>>();

      for(var site in sites) {
         results.Add(GetSiteResultAsync(site)); 
      }
      return results.WhenAll(sites);
   }

If you notice, in 1st code fragment, even by adding more threads you will not achieve any performance benefit, because all operations are sequential. But in 2nd code fragment, in the same ASP.NET thread pool, it will perform better as all tasks are created and executed in parallel.

code of conduct - report abuse