C#-----创建线程的多种方式
1.Thread
Thread创建和控制线程,设置其优先级并获取其状态
1.1 不带参数
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace ConsoleApp5 { class Program { static void Main(string[] args) { Thread thread = new Thread(new ThreadStart(CreateThread)); thread.Name = "线程一"; thread.IsBackground = true; thread.Start(); } static void CreateThread() { for (int i=1;i<=20;i++) { Console.WriteLine(Thread.CurrentThread.Name+":"+i); } } } }
1.2 带参数ParameterizedThreadStart
using System; using System.Threading; namespace ConsoleApp5 { class Program { static void Main(string[] args) { Thread thread = new Thread(new ParameterizedThreadStart(CreateThread)); thread.IsBackground = true; thread.Start("线程二"); Console.ReadLine(); } static void CreateThread(Object threadName) { Thread.CurrentThread.Name = threadName.ToString(); for (int i = 1; i <= 20; i++) { Console.WriteLine(Thread.CurrentThread.Name + ":" + i); } } } }
2.Task
Task类的表示单个操作不会返回一个值,通常以异步方式执行
2.1 直接New创建
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ConsoleApp5 { class Program { static void Main(string[] args) { Task task = new Task(() => { Console.WriteLine("可以直接写代码,也可以调用方法"); CreateTask(); }); task.Start(); Console.ReadLine(); } static void CreateTask() { Thread.CurrentThread.Name = "线程一"; for (int i = 1; i <= 20; i++) { Console.WriteLine(Thread.CurrentThread.Name + ":" + i); } } } }
2.2 使用Factory工厂创建
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ConsoleApp5 { class Program { static void Main(string[] args) { //Factory提供对用于创建Task的工厂方法的访问 Task.Factory.StartNew(() => { Console.WriteLine("可以直接写代码,也可以调用方法"); CreateTask(); }); Console.ReadLine(); } static void CreateTask() { Thread.CurrentThread.Name = "线程一"; for (int i = 1; i <= 20; i++) { Console.WriteLine(Thread.CurrentThread.Name + ":" + i); } } } }
2.3 使用Run方法
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ConsoleApp5 { class Program { static void Main(string[] args) { //将在线程池上运行的指定工作排队,并返回代表该工作的Task对象 Task.Run(() => { Console.WriteLine("可以直接写代码,也可以调用方法"); CreateTask(); }); Console.ReadLine(); } static void CreateTask() { Thread.CurrentThread.Name = "线程一"; for (int i = 1; i <= 20; i++) { Console.WriteLine(Thread.CurrentThread.Name + ":" + i); } } } }