Task 和Thread在效率上有什麼區別
阿新 • • 發佈:2021-06-30
Task執行帶引數的函式
Task<Int32> task = Task.Run(() => fun("s", 9));
函式定義:
private Int32 frun(string s, int m)
{
return 0;
}
using System; using System.Threading; using System.Threading.Tasks; namespace ConsoleApplication1 { static class Program { static void Main(string[] args) {for (var i = 1; i <= 50; i++) TestTask(i); for (var i = 1; i <= 50; i++) TestThreadPool(i); for (var i = 1; i <= 50; i++) TestThread(i); Console.ReadLine(); } private static void TestThread(inti) { Console.WriteLine("Thread {0} start.", i); new Thread(h => { Thread.Sleep(5000); Console.WriteLine("-------------------Thread {0} end.", i); }).Start(); } private static void TestThreadPool(inti) { Console.WriteLine("ThreadPool {0} start.", i); ThreadPool.QueueUserWorkItem(h => { Thread.Sleep(5000); Console.WriteLine("-------------------ThreadPool {0} end.", i); }); } private static void TestTask(int i) { Console.WriteLine("Task {0} start.", i); new Task(() => { Thread.Sleep(5000); Console.WriteLine("-------------------Task {0} end.", i); }).Start(); } } }
可以看看誰最先列印 ------------------end。 你可以看到,Thread 完勝 Task。
這只是因為Task是用了執行緒池來控制的,開始的時候執行緒池內只有預設數量的執行緒,隨著任務增多執行緒池在增大容量(具體策略不太瞭解),所以後面幾個執行緒啟動晚了。 而Thread是全部一起啟動的,所以幾乎同時完成。 這是出於穩定性考慮的設計,Task的設計是用來解決實際問題的,比如網路下載、資料讀寫,瓶頸在於網路或儲存的速度,並且要保證穩定。 上面的測試太理論,沒有太多實際意義 當然引起思考的作用還是有的...
TASK注重點在並行~ 所以如果你是工作在多核情況下,那麼task或許是你最好的選擇了,但是thread卻無法實現自動化的並行操作~ task是基於threadPool的,所以相比thread來說,就算再單核,我也依然覺得task這種方式會比thread強~