一、使用線程池中線程的任務啟動方式
線程池提供了一個后台線程的池,獨自管理線程,按需增加或減少線程池中的線程數。線程池中的線程用於執行一些動作后仍然返回線程池中。
- 示例:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.IO; namespace TaskSamples { class Program { static void Main() { TasksUsingThreadPool(); Console.ReadLine(); } static void TasksUsingThreadPool() { var tf = new TaskFactory(); Task t1 = tf.StartNew(TaskMethod, "using a task factory"); Task t2 = Task.Factory.StartNew(TaskMethod, "factory via a task"); var t3 = new Task(TaskMethod, "using a task constructor and Start"); t3.Start(); Task t4 = Task.Run(() => TaskMethod("using the Run method")); } static object taskMethodLock = new object(); static void TaskMethod(object title) { lock (taskMethodLock) { Console.WriteLine(title); Console.WriteLine("Task id: {0}, thread: {1}", Task.CurrentId == null ? "no task" : Task.CurrentId.ToString(), Thread.CurrentThread.ManagedThreadId); Console.WriteLine("is pooled thread: {0}", Thread.CurrentThread.IsThreadPoolThread); Console.WriteLine("is background thread: {0}", Thread.CurrentThread.IsBackground); Console.WriteLine(); } } } }
- 實例化TaskFactory類,將要執行的方法作為參數傳遞給實例的StartNew方法
- 使用Task類的靜態屬性TaskFactory訪問TaskFactory,並調用其StartNew方法
- 使用Task類的構造函數實例化Task對象,並調用其Start方法
- 調用Task類的靜態方法Run,參數為一個Action委托
var tf = new TaskFactory(); Task t1 = tf.StartNew(TaskMethod, "using a task factory");
Task t2 = Task.Factory.StartNew(TaskMethod, "factory via a task");
var t3 = new Task(TaskMethod, "using a task constructor and Start"); t3.Start();
Task t4 = Task.Run(() => TaskMethod("using the Run method"));