Does Task.Delay start a new thread? Does Task.Delay start a new thread? multithreading multithreading

Does Task.Delay start a new thread?


The Task library is designed more for managing blocking tasks without blocking an entire workflow (task asynchronism, confusingly called "task parallel" by Microsoft), and not for doing large blocks of concurrent computation (parallel execution).

The task library uses a scheduler and queues jobs ready for execution. When jobs are run, they will do so on a thread-pool thread, and these are very limited in number. There is logic to expand the thread count, but unless you have hundreds of CPU cores, it's going to stay a low number.

So to answer the question, some of your tasks are queued up waiting for a thread from the pool, while the other delayed tasks have been issued by the scheduler.

The scheduler and thread-pool logic can be changed at runtime, but if you are trying to get lots of computation done quickly Task isn't right for the job. If you want to deal with lots of slow resources (like disk, database, or internet resources) Task may help keep an app responsive.

If you just want to learn about Task try these:


On .NET Framework Desktop.

In short, there this special VM thread which periodically checks queue of timers and runs timers' delegates on thread pool queue. Task.Delay does not create new Thread, but still may be heavy, and no guaranties on order of execution or being precise about deadlines. And as I understand, passing cancellation Task.Delay may end up in just removing item from collection, with no thread pool work queued.

Task.Delay scheduled as DelayPromise by creating new System.Threading.Timer. All timers are stored in AppDomain singleton of TimerQueue. Native VM timer used to callback .NET to check if need to fire any timers from queue. Timer delegates scheduled for execution via ThreadPool.UnsafeQueueUserWorkItem.

From performance point of view, it seems better to cancel delay if delay ends earlier:

open System.Threadingopen System.Threading.Tasks// takes 0.8% CPUwhile true do  Thread.Sleep(10)  Task.Delay(50)// takes 0.4% CPUlet mutable a = new CancellationTokenSource()while true do  Thread.Sleep(10)  a.Cancel()  a.Dispose()  a <- new CancellationTokenSource()  let token = a.Token  Task.Delay(50,token)