DEV Community

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

Collapse
 
akashkava profile image
Akash Kava • Edited

Task is usually a small computation operation. Typically, it executes some logic and then it waits for an IO operation to proceed further. So when you are processing logic which requires dealing with multiple services outside the program, Task is useful.

But if you are performing a long operation and you need priority over other small tasks, then you need to create thread. Typically operations that involve processing huge computation on large dataset in memory.

Though you can still breakdown huge computation into tasks, but not all computation go well with tasks, you have to measure, tasks come with more overhead which may slow down computation. Best way is to measure performance by profiling the code.

Collapse
 
darknada profile image
DarkNada

First of all, thank you for your explanation. In ASP.NET documentation, I read that asynchronous methods use threads from existing thread group of ASP.NET. The API I am working on is a simple web api to retrieve records from a IMDG. For that I used asynchronous method. My question is, should I make the application threaded to make the performance better or does the async method make the performance optimisation? Can we use both asynchronisation and thread concept for the same method?

Collapse
 
akashkava profile image
Akash Kava

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.