Thread space overhead
- The thread kernel object. Contains context information. 32-bit system occupies 700 bytes
- Thread environment block. Including thread Exception Handling links. 32-bit system occupies 4 kb
- User Mode stack. Save method parameters, local variables, and returned values
- Kernel Mode stack. When calling the kernel-mode function of the operating system, the system copies the function parameters from the user mode stack to the kernel mode stack. 32-bit system occupied by 12kb
Thread time overhead
- During the creation, the system initializes the above memory space one after another
- CLR loads DLL to the dllmain method and transmits the connection flag
- Thread context switch
- Enter Kernel Mode
- Save the context information to the executing thread kernel object.
- The system obtains a spinlock and determines the next thread to be executed. Release the spinlock. If the next thread is not in the same process, virtual address exchange is required.
- Load context information from the kernel object of the executed thread
- Exit Kernel Mode
When the thread pool is used, the CLR will not destroy this thread, but will keep this thread for a period of time.
using System;using System.Diagnostics;using System.Threading;namespace ConsoleApplication1{ class Program { static void Main(string[] args) { var p = new Program(); Stopwatch sw = new Stopwatch(); sw.Start(); p.Thread(); sw.Stop(); Console.WriteLine(sw.ElapsedTicks); sw.Restart(); p.Pool(); sw.Stop(); Console.WriteLine(sw.ElapsedTicks); Console.ReadKey(); } void Thread() { for (int i = 0; i < 10; i++) { var worker = new Thread(() => { //Console.WriteLine("Thread Do"); }); worker.Start(); } } void Pool() { for (int i = 0; i < 10; i++) { ThreadPool.QueueUserWorkItem(state => { //Console.WriteLine("Pool Do"); }); } } }}
Use threadpool instead of Thread