Introduction to asynchronous Task programming, Thread multi-Thread programming, and task multi-Thread programming
When I was a beginner, I searched online. I saw many articles with titles related to replacing thread with tasks. I always thought that Task and thread are the same. In fact, task is. asynchronous programming proposed by net4.0, before. net1.0 has delegete. beginInoke (XXXX), and. EAP in net2.0, in the latest 4.5, has new asynchronous programming such as async and await. Thread and Threadpool are multi-threaded programming.
However, the Task also pushes the Task to the thread pool.
1 static void Main(string[] args) 2 { 3 for(int i=0;i<5;i++) 4 { 5 var task1 = Task.Factory.StartNew(() => Run()); 6 var task2 = Task.Factory.StartNew(() => Run()); 7 var task3 = Task.Factory.StartNew(() => Run()); 8 var task4 = Task.Factory.StartNew(() => Run()); 9 }10 Console.ReadKey();11 }12 13 static void Run()14 {15 Thread.Sleep(100);16 Console.WriteLine("TaskId:{0} ThreadId:{1}", Task.CurrentId, Thread.CurrentThread.ManagedThreadId);17 }
The running result is:
Compared with Threadpool, tasks can obtain return values and have more control. Threadpool consumes less resources. If you only need to throw tasks to the thread pool, none of the other tasks will be involved, we recommend that you use Threadpool.