Saturday 1 April 2017


Creating threads can prove to be expensive, this is why there's a threadpool, class who's purpose is to keep a bunch of threads ready for your use to do threading stuff:
  • execute tasks
  • post work items
  • process asynchronous IO
  • etc
Threads created by the threadpool class are by default background threads, meaning your application won't wait for them if all foreground threads finish the app will close

using System;
using System.Threading;

namespace pc.threadpoolExample
    class Program
        static void Main(string[] args)
            //create background thread via threadpool
            ThreadPool.QueueUserWorkItem(o => {
                Thread.Sleep(500);//fires before main finishes
                Console.WriteLine("Hello from the thread pool 1");

            //create background thread via threadpool
            ThreadPool.QueueUserWorkItem(o=> {
                Thread.Sleep(2000);// never fires, because main finishes
                Console.WriteLine("Hello from the thread pool 2");

            var t = new Thread(() => {
                Console.WriteLine("hello from foregorund thread");
            //start explicit thread

            //join thread back to main

            Console.WriteLine("Main finished");

generally you wont create threads explicitly or via the threadpool class, odds are you'll leverage

  • the Task Parallel library (TPL) 
  • the async/await keywords which abstract the TPL. 
  • the Asynchronous Pattern Model
  • the Event based Asynchronous Pattern   
  • the Task based Asynchronous Pattern Model