1.异步委托开启线程
1 public static void Main(string[] args) 2 { 3 Action<int,int> a=add; 4 a.BeginInvoke(3,4,null,null);//前两个是add方法的参数,后两个可以为空
5 Console.WriteLine("main()"); 6 Console.ReadKey(); 7 } 8 static void add(int a,int b) 9 { 10 Console.WriteLine(a+b); 11 }
2.通过Thread类开启线程
1 public class Program 2 { 3 public static void Main(string[] args) 4 { 5 Thread t1; 6 Thread t2; 7 t1 = new Thread(SetInfo1); 8 t2 = new Thread(SetInfo2); 9 t1.Start(); 10 //线程睡眠 11 //t1.Join(1000); 12 //挂起线程
13 t1.Suspend(); 14 //继续执行线程
15 t1.Resume(); 16 //结束线程 17 //t1.Abort();
18
19 t2.Start(); 20 Console.ReadKey(); 21 } 22 //奇数线程
23 public static void SetInfo1() 24 { 25 for (int i = 0; i < 100; i++) 26 { 27 if (i % 2 != 0) 28 { 29 Console.WriteLine("奇数为" + i); 30 } 31 } 32 } 33 //偶数线程
34 public static void SetInfo2() 35 { 36 for (int i = 0; i < 100; i++) 37 { 38 if (i % 2 == 0) 39 { 40 Console.WriteLine("偶数为" + i); 41 } 42 } 43 } 44 }
3.通过线程池开启线程
1 //线程池可以看做容纳线程的容器;一个应用程序最多只能有一个线程池;ThreadPool静态类通过QueueUserWorkItem()方法将工作函数排入线程池; 每排入一个工作函数,就相当于请求创建一个线程; 2 //线程池的作用: 3 //1、线程池是为突然大量爆发的线程设计的,通过有限的几个固定线程为大量的操作服务,减少了创建和销毁线程所需的时间,从而提高效率。 4 //2、如果一个线程的时间非常长,就没必要用线程池了(不是不能作长时间操作,而是不宜。),况且我们还不能控制线程池中线程的开始、挂起、和中止
5 public class Program 6 { 7 public static void Main(string[] args) 8 { 9 ThreadPool.QueueUserWorkItem(new WaitCallback(TestThreadPool), new string[] { "hjh" }); 10 Console.ReadKey(); 11 } 12 public static void TestThreadPool(object state) 13 { 14 string[] arry = state as string[];//传过来的参数值
15 int workerThreads = 0; 16 int CompletionPortThreads = 0; 17 ThreadPool.GetMaxThreads(out workerThreads, out CompletionPortThreads); 18 Console.WriteLine(DateTime.Now.ToString() + "---" + arry[0] + "--workerThreads=" + workerThreads + "--CompletionPortThreads" + CompletionPortThreads); 19 } 20 }
4.通过任务Task开启线程
1 public class Program 2 { 3 public static void Main(string[] args) 4 { 5 Task task = new Task(DownLoadFile_My); 6 task.Start(); 7 Console.ReadKey(); 8 } 9 static void DownLoadFile_My() 10 { 11 Console.WriteLine("开始下载...线程ID:"+Thread.CurrentThread.ManagedThreadId); 12 Thread.Sleep(500); 13 Console.WriteLine("下载完成!"); 14 } 15 }
1 new Thread(() => 2 { 3 try 4 { 5 //运行的代码 6 } 7 catch (Exception ex) 8 { 9 } 10 }).Start();