Saturday, 1 April 2017

Threadpool

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(() => {
                Thread.Sleep(1000);
                Console.WriteLine("hello from foregorund thread");
            });
       
            //start explicit thread
            t.Start();

            //join thread back to main
            t.Join();

            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