Why do such delays occur when working with Task?

using System; using System.Threading; using System.Threading.Tasks; class Program { static void SomethingLong() { Thread.Sleep(30000); } static void Main(string[] args) { for (int i = 0; i < 20; ++i) Task.Run(() => { Console.Write("="); SomethingLong(); }); for (int i = 0; i < 20; ++i) (new Thread(() => { Console.Write("-"); SomethingLong(); })).Start(); for (int i = 1; i <= 20; ++i) { Thread.Sleep(1000); Console.Write(i.ToString()); } } } 

1 answer 1

Because tasks use a pool of threads. If there are no threads left when creating a task in the pool, then the CLR chooses to create a new one or puts a task in the queue.

If you know that the task will run for a long time and others should not wait for it, you can use the Task.Factory.StartNew method with the TaskCreationOptions.LongRunning option.