Threads And ThreadPools


Intro

My notes on C# threads

The Thread Class implements threads in C#

 


Documentation

 


Tips And Tidbits

 

  • Threads can execute either in the foreground or in the background.

  • A background thread will terminate if all foreground threads in the process are finished.

  • Use the ThreadPool class to execute code on worker threads that are managed by the common language runtime.

  • Worker threads run in the background.

  • Setting the IsBackground property to TRUE at any time will cause thread to run in background.

  • The method/delegate to execute as a thread must be declared as static (just like a program’s Main() method)

 

  • The thread pool enables you to use threads more efficiently by providing your application with a pool of worker threads that are managed by the system

  • The thread pool uses background threads, which do not keep the application running if all foreground threads have terminated.

  • There is one thread pool per process.

  • A process can call the GetMaxThreads method to determine the number of threads.

    • The number of threads in the thread pool can be changed by using the SetMaxThreads method.

  • Each thread uses the default stack size and runs at the default priority.

 


Examples

 

DotNetFiddle example: https://dotnetfiddle.net/FwEzxA

using System; using System.Threading; public class Program { public static void Main() { Console.WriteLine("Main thread is starting..."); var thread1 = new Thread(SpawnedThread) { IsBackground = false}; thread1.Start(); Console.WriteLine("Main thread ({0}) exiting...", Thread.CurrentThread.ManagedThreadId); } private static void SpawnedThread() { Console.WriteLine("Spawned thread ({0}) is now running in {1}", Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.IsBackground ? "background" : "foreground"); } }