当前位置:网站首页>C multithreading learning note 3

C multithreading learning note 3

2022-06-10 13:58:00 HollowKnightZ

ThreadPool

Thread => One asynchronous task starts one Thread, Proprietary
ThreadPool => To start an asynchronous task, you only need to borrow threads from it , Return after use

ThreadPool How to use

ThreadPool.QueueUserWorkItem((obj) =>
{
    
var Fun = obj as Func<string>;
Console.WriteLine(" Sub thread :" + Thread.CurrentThread.ManagedThreadId + " context:" + Fun());
}, new Func<string>(() => "hello world"));
Console.WriteLine(" The main thread :" + Thread.CurrentThread.ManagedThreadId);
Console.ReadKey();

ThreadPool And Thread The difference between

10 A mission , use Thread To do it , Need to open 10 individual Thread, If you use ThreadPool To do it , Only need to 10 Tasks are assigned to the thread pool .
Thread The analytic function of is as follows :

~Thread()
{
    
	this.InternalFinalize();
}

From the destructor we can see this.InternalFinalize(); That is to say, after destruction , First in Terminator , The thread is destroyed , But not by GC(Garbage Collection) Recycling , The resources that should be occupied will still be occupied . While using ThreadPool There will be no dead threads , They are initialized by default .

Threads in the thread pool : Worker threads and IO Threads

 Insert picture description here
The worker thread : For general asynchronous tasks , It doesn't involve the network , File these IO operation 【 open Sender call 】
IO Threads : Generally used in documents , The Internet IO On .【CLR call 】

summary

ThreadPool It can be used 8 Threads to solve thread 10 What a thread does , Save space and time .
Time => Notify each managed and unmanaged DLL
Space => teb,osthread structure , Stack

原网站

版权声明
本文为[HollowKnightZ]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206101342364240.html